Add the account area and account-synced Appearance preferences
CI / verify (pull_request) Successful in 1m10s
CI / infrastructure-smoke (pull_request) Successful in 34s
CI / package-release (pull_request) Successful in 50s
CI / migration-smoke (pull_request) Successful in 2m26s
CI / image-build (pull_request) Successful in 1m12s
CI / deploy-smoke (same-origin) (pull_request) Successful in 42s
CI / package-publication (pull_request) Successful in 54s
CI / deploy-smoke (split) (pull_request) Successful in 3m17s

Stage 1 PR 6 (ADR 0062). /account shows who is signed in; /account/appearance
chooses System, Light, or Dark and reduced motion (System, Reduce, Allow).

- Core: ekklesia_core_user_preference, one typed, CHECK-constrained,
  nullable column per preference (null = never chosen), migration
  0008_user_preferences (additive), @ekklesia/core/account store, and the
  authenticated-baseline permission core.account.self.manage.
- API: GET /api/v1/account (name, email, preferences) and partial
  PATCH /api/v1/account/preferences, self-only by construction: no user id
  is accepted anywhere; trusted Origin and body limit on the mutation.
- Shell: the account control shows name, email, and initials (never the
  unvetted image URL) and offers Account, Appearance, Sign out; native
  radio groups apply a choice at once through the ADR 0060 controller and
  save it; the server's answer wins and a failed save reverts.
- First paint: a classic, same-origin, render-blocking appearance.js in
  <head> applies a two-word localStorage cache before paint (no inline
  script, CSP unchanged). The account replaces the cache on every load,
  sign-out clears it, and other tabs follow via the storage event.
- Deploy smoke: real-Chromium checks for light/dark, OS emulation,
  overrides, reload persistence, pre-paint, Shadow DOM modules, reduced
  motion, the display staying light, and phone width; the browser
  container gets a 512 MiB /dev/shm so a long session no longer fails
  requests with ERR_INSUFFICIENT_RESOURCES.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
ekklesia
2026-10-14 23:56:50 -05:00
co-authored by Claude Opus 5.5
parent 8571e6854c
commit cd0287537e
88 changed files with 6404 additions and 158 deletions
+1
View File
@@ -28,6 +28,7 @@
},
"devDependencies": {
"@biomejs/biome": "2.5.3",
"@ekklesia/design-tokens": "workspace:*",
"@ekklesia/module-ui-host": "workspace:*",
"@ekklesia/module-ui-sdk": "workspace:*",
"@ekklesia/typescript-config": "workspace:*",
+157
View File
@@ -0,0 +1,157 @@
import { isAuthenticatedPrincipal } from "@ekklesia/contracts";
import {
type AccountPreferences,
type AccountStore,
AccountStoreError,
parseAccountPreferencesUpdate,
} from "@ekklesia/core/account";
import { CORE_ACCOUNT_SELF_MANAGE } from "@ekklesia/core/authorization";
import { type Context, Hono } from "hono";
import {
type AuthorizationMiddlewareOptions,
getAuthorizedPrincipal,
requirePermission,
requireTrustedOrigin,
} from "./authorization-middleware.js";
import { CORE_MUTATION_MAX_BODY_BYTES, platformBodyLimit } from "./body-limits.js";
export const ACCOUNT_PATH = "/api/v1/account";
export const ACCOUNT_PREFERENCES_PATH = `${ACCOUNT_PATH}/preferences`;
/** `GET /api/v1/account`: the signed-in person's own account, as the account area shows it. */
export interface AccountResponse {
readonly name: string;
readonly email: string;
readonly preferences: AccountPreferences;
}
export interface CreateAccountRoutesOptions extends AuthorizationMiddlewareOptions {
readonly store: AccountStore;
readonly trustedOrigins: ReadonlySet<string>;
}
function sanitizedFailure(c: Context, status: 400 | 403 | 404 | 503, code: string): Response {
c.header("Cache-Control", "no-store");
return c.json({ code }, status);
}
/** Maps the store's own sanitized codes onto HTTP without inventing a second vocabulary. */
function storeFailure(
c: Context,
error: unknown,
fallback: "ACCOUNT_READ_FAILED" | "ACCOUNT_WRITE_FAILED",
): Response {
if (error instanceof AccountStoreError) {
if (error.code === "ACCOUNT_NOT_FOUND") {
return sanitizedFailure(c, 404, error.code);
}
if (error.code === "ACCOUNT_PREFERENCES_INVALID") {
return sanitizedFailure(c, 400, "INVALID_REQUEST");
}
return sanitizedFailure(c, 503, error.code);
}
return sanitizedFailure(c, 503, fallback);
}
async function readJsonBody(c: Context): Promise<unknown> {
try {
return (await c.req.json()) as unknown;
} catch {
return undefined;
}
}
/**
* A signed-in person's own account (ADR 0062): who they are signed in as, and their own
* preferences.
*
* ## Self-only by construction
*
* Neither route accepts a user id — not in the path, not in the query, not in the body. The account
* is always the one the **session** names, so there is no request that could read or change anyone
* else's, whatever permission the caller holds. A body that names any key besides a known
* preference is refused whole.
*
* ## Authorization
*
* Both routes require `core.account.self.manage`, whose baseline is `authenticated`: every
* signed-in person may manage their own account, and needs no church-management permission to do
* so. An anonymous caller and a paired device are refused (`403`). Changing a preference is a
* mutation like any other Core mutation: an exact trusted `Origin` and a bounded body are checked
* before authorization work begins.
*
* ## What the browser learns
*
* Name, email, and preferences — exactly what the account area shows, and nothing else. Not the
* account's image URL, verification state, timestamps, or any credential. Responses are per-person
* and never cached.
*/
export function createAccountRoutes(options: CreateAccountRoutesOptions): Hono {
const routes = new Hono();
const requireSelf = requirePermission(options, CORE_ACCOUNT_SELF_MANAGE);
const requireOrigin = requireTrustedOrigin(options.trustedOrigins);
const mutationBodyLimit = platformBodyLimit(CORE_MUTATION_MAX_BODY_BYTES);
routes.get(ACCOUNT_PATH, requireSelf, async (c) => {
c.header("Cache-Control", "no-store");
c.header("Vary", "Origin, Cookie");
const principal = getAuthorizedPrincipal(c);
// Unreachable through the `authenticated` baseline, which only a person satisfies; checked
// again so the account read can never be keyed by anything but a person's own session.
if (!isAuthenticatedPrincipal(principal)) {
return sanitizedFailure(c, 403, "AUTHORIZATION_DENIED");
}
try {
const account = await options.store.readAccount(principal.userId);
if (!account) {
return sanitizedFailure(c, 404, "ACCOUNT_NOT_FOUND");
}
return c.json(
{
email: account.email,
name: account.name,
preferences: {
appearance: account.preferences.appearance,
motion: account.preferences.motion,
},
} satisfies AccountResponse,
200,
);
} catch (error) {
return storeFailure(c, error, "ACCOUNT_READ_FAILED");
}
});
routes.patch(
ACCOUNT_PREFERENCES_PATH,
requireOrigin,
mutationBodyLimit,
requireSelf,
async (c) => {
c.header("Cache-Control", "no-store");
c.header("Vary", "Origin, Cookie");
const principal = getAuthorizedPrincipal(c);
if (!isAuthenticatedPrincipal(principal)) {
return sanitizedFailure(c, 403, "AUTHORIZATION_DENIED");
}
const update = parseAccountPreferencesUpdate(await readJsonBody(c));
if (!update) {
return sanitizedFailure(c, 400, "INVALID_REQUEST");
}
try {
const preferences = await options.store.updatePreferences(principal.userId, update);
return c.json(
{
appearance: preferences.appearance,
motion: preferences.motion,
} satisfies AccountPreferences,
200,
);
} catch (error) {
return storeFailure(c, error, "ACCOUNT_WRITE_FAILED");
}
},
);
return routes;
}
+20
View File
@@ -8,6 +8,7 @@ import type {
AuthorizationStore,
PermissionRegistry,
} from "@ekklesia/core/authorization";
import type { AccountStore } from "@ekklesia/core/account";
import type { DashboardStore } from "@ekklesia/core/dashboard";
import type { DeviceStore } from "@ekklesia/core/devices";
import { type EkklesiaIdentityRuntime, IdentityRuntimeError } from "@ekklesia/core/identity";
@@ -28,6 +29,7 @@ import type { Context, MiddlewareHandler } from "hono";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { AUTH_REQUEST_MAX_BODY_BYTES, platformBodyLimit } from "./body-limits.js";
import { createAccountRoutes } from "./account-routes.js";
import type { DashboardHostAssets } from "./dashboard-host-assets.js";
import { createDashboardHostRoutes } from "./dashboard-host-routes.js";
import { createDashboardRoutes } from "./dashboard-routes.js";
@@ -141,6 +143,10 @@ export interface CreateApiAppOptions {
* presentation only — nothing reachable through this store influences discovery, dependency
* ordering, module startup, or any authorization decision. */
readonly dashboard: DashboardStore;
/** Core's persistence for a signed-in person's own account summary and preferences (ADR 0062).
* Required like `dashboard`: every installation has accounts. Reachable only through routes that
* take the account from the session, never from the request. */
readonly account: AccountStore;
/**
* The built Dashboard's two files, read once by production startup (ADR 0044). Required rather
* than optional, unlike `displayHostAssets`: every installation has a Dashboard, and a missing
@@ -469,6 +475,20 @@ export function createApiApp(options: CreateApiAppOptions): Hono {
}),
);
// The signed-in person's own account and preferences (ADR 0062). Self-only by construction: the
// account is always the session's, and no request value can name another. See
// `./account-routes.js`.
app.route(
"/",
createAccountRoutes({
evaluator: options.authorization.evaluator,
registry: options.authorization.registry,
runtime,
store: options.account,
trustedOrigins: allowedOrigins,
}),
);
// Mounted before module routes and, critically, under its own sibling prefix: `/api/v1/modules/`
// belongs entirely to installed modules, so the platform's own lifecycle resource lives beside it
// rather than inside it. See `./module-lifecycle-routes.js`.
+24 -5
View File
@@ -3,7 +3,9 @@ import { readFile } from "node:fs/promises";
import { dashboardHostAssetUrls } from "@ekklesia/shell/dashboard-assets";
/**
* The two immutable, platform-owned files that make up the built Ekklesia Dashboard (ADR 0044).
* The three immutable, platform-owned files that make up the built Ekklesia Dashboard (ADR 0044):
* the page, its application script, and the small pre-paint appearance script the page loads in
* `<head>` (ADR 0062).
*
* Exactly the model `./display-host-assets.js` uses: read once, before the HTTP listener is bound,
* from the exact URLs the surface package exports. Request input is never involved in this read, the
@@ -16,6 +18,8 @@ export interface DashboardHostAssets {
readonly htmlEtag: string;
readonly script: string;
readonly scriptEtag: string;
readonly appearanceScript: string;
readonly appearanceScriptEtag: string;
}
/** A startup failure with a fixed, non-secret shape. The originating filesystem exception, package
@@ -42,11 +46,21 @@ function strongEtag(text: string): string {
* can never be paired with an ETag from another. Empty output is a failed shell build rather than a
* valid page that can never render anything.
*/
export function createDashboardHostAssets(html: string, script: string): DashboardHostAssets {
if (html.trim().length === 0 || script.trim().length === 0) {
export function createDashboardHostAssets(
html: string,
script: string,
appearanceScript: string,
): DashboardHostAssets {
if (
html.trim().length === 0 ||
script.trim().length === 0 ||
appearanceScript.trim().length === 0
) {
throw new DashboardHostAssetError();
}
return Object.freeze({
appearanceScript,
appearanceScriptEtag: strongEtag(appearanceScript),
html,
htmlEtag: strongEtag(html),
script,
@@ -92,7 +106,7 @@ export function renderDashboardPage(html: string, apiOrigin: string): string {
return parts.join(`<meta content="${escaped}" name="ekklesia-api-origin" />`);
}
/** Loads only the two surface-declared files, and renders the API origin into the page. A missing,
/** Loads only the three surface-declared files, and renders the API origin into the page. A missing,
* unreadable, or incompatible build fails startup rather than leaving an API whose own origin answers
* `/` with a 404 or a page that cannot find its API. */
export async function loadDashboardHostAssets(apiOrigin: string): Promise<DashboardHostAssets> {
@@ -101,7 +115,12 @@ export async function loadDashboardHostAssets(apiOrigin: string): Promise<Dashbo
// rejected sibling read is left running after this function has already failed.
const html = await readFile(new URL(dashboardHostAssetUrls.html), "utf8");
const script = await readFile(new URL(dashboardHostAssetUrls.script), "utf8");
return createDashboardHostAssets(renderDashboardPage(html, apiOrigin), script);
const appearanceScript = await readFile(new URL(dashboardHostAssetUrls.appearance), "utf8");
return createDashboardHostAssets(
renderDashboardPage(html, apiOrigin),
script,
appearanceScript,
);
} catch {
throw new DashboardHostAssetError();
}
+20 -2
View File
@@ -17,6 +17,8 @@ import { createDashboardHostAssets, type DashboardHostAssets } from "./dashboard
*/
export const DASHBOARD_HOST_PAGE_PATH = "/";
export const DASHBOARD_HOST_SCRIPT_PATH = "/assets/ekklesia-dashboard/app.js";
/** The pre-paint appearance script (ADR 0062), beside the application script. */
export const DASHBOARD_HOST_APPEARANCE_SCRIPT_PATH = "/assets/ekklesia-dashboard/appearance.js";
/**
* Revalidate-always with a strong `ETag`, exactly the module UI and display-host script policy. The
@@ -56,8 +58,12 @@ export class DashboardHostConfigurationError extends Error {
* a composition can never pair bytes with a validator computed from different bytes. */
function snapshotAssets(input: DashboardHostAssets): DashboardHostAssets {
try {
const snapshot = createDashboardHostAssets(input.html, input.script);
if (snapshot.htmlEtag !== input.htmlEtag || snapshot.scriptEtag !== input.scriptEtag) {
const snapshot = createDashboardHostAssets(input.html, input.script, input.appearanceScript);
if (
snapshot.htmlEtag !== input.htmlEtag ||
snapshot.scriptEtag !== input.scriptEtag ||
snapshot.appearanceScriptEtag !== input.appearanceScriptEtag
) {
throw new DashboardHostConfigurationError();
}
return snapshot;
@@ -169,5 +175,17 @@ export function createDashboardHostRoutes(
),
);
// Same-origin, revalidated like the application script, and carrying nothing but code: the
// person's cached choice lives in their browser and is read by this script, never served by it.
routes.get(DASHBOARD_HOST_APPEARANCE_SCRIPT_PATH, (c) =>
fixedAsset(
c.req.header("if-none-match"),
snapshot.appearanceScript,
snapshot.appearanceScriptEtag,
"text/javascript; charset=utf-8",
{},
),
);
return routes;
}
+3
View File
@@ -1,4 +1,5 @@
import type { ModuleDatabaseExecutor, ModuleId } from "@ekklesia/contracts";
import { type AccountDrizzleDatabase, createAccountDrizzleView } from "@ekklesia/core/account";
import {
type AuthorizationDrizzleDatabase,
createAuthorizationDrizzleView,
@@ -21,6 +22,7 @@ import {
} from "@ekklesia/core/modules";
export interface ApiDatabaseHandle {
readonly account: AccountDrizzleDatabase;
readonly authorization: AuthorizationDrizzleDatabase;
readonly devices: DeviceDrizzleDatabase;
readonly dashboard: DashboardDrizzleDatabase;
@@ -74,6 +76,7 @@ export function createApiDatabase(
const { close, pool } = createValidatedPostgresPool(databaseUrl, options);
return Object.freeze({
account: createAccountDrizzleView(pool),
authorization: createAuthorizationDrizzleView(pool),
close,
devices: createDeviceDrizzleView(pool),
+3
View File
@@ -6,6 +6,7 @@ import {
createAuthorizationEvaluator,
createAuthorizationStore,
} from "@ekklesia/core/authorization";
import { createAccountStore } from "@ekklesia/core/account";
import { createDashboardStore } from "@ekklesia/core/dashboard";
import { createDeviceStore } from "@ekklesia/core/devices";
import { type HostEnvironment, loadHostConfiguration } from "@ekklesia/core/host";
@@ -639,6 +640,8 @@ export async function startApi(
},
// A typed view over the same single pool as identity, authorization, and the module facade.
dashboard: createDashboardStore(databaseHandle.dashboard),
// The same pool again: a person's own account summary and preferences (ADR 0062).
account: createAccountStore(databaseHandle.account),
dashboardHostAssets,
// The app is only composed after `startDiscoveredModuleRuntime` resolved, so module startup
// has completed whenever it can answer; it stops counting as complete once shutdown begins.
+340
View File
@@ -0,0 +1,340 @@
import {
ANONYMOUS_PRINCIPAL,
createAuthenticatedPrincipal,
createDevicePrincipal,
type EkklesiaPrincipal,
parseEkklesiaUserId,
} from "@ekklesia/contracts";
import { ACCOUNT_APPEARANCES, ACCOUNT_MOTION_PREFERENCES } from "@ekklesia/core/account";
import {
type AuthorizationStore,
CORE_ACCOUNT_SELF_MANAGE,
CORE_PERMISSION_REGISTRY,
createAuthorizationEvaluator,
} from "@ekklesia/core/authorization";
import type { EkklesiaIdentityRuntime } from "@ekklesia/core/identity";
import {
composePlatformPermissionRegistry,
createModuleUiPublicationRegistry,
EMPTY_MODULE_REALTIME_REGISTRY,
type LegacyModuleRuntimeServices,
type ModuleDatabase,
} from "@ekklesia/core/modules";
import { EKKLESIA_APPEARANCES, EKKLESIA_MOTION_PREFERENCES } from "@ekklesia/design-tokens";
import { describe, expect, it, vi } from "vitest";
import { ACCOUNT_PATH, ACCOUNT_PREFERENCES_PATH } from "../src/account-routes.js";
import { createApiApp } from "../src/app.js";
import {
createInMemoryAccountStore,
type InMemoryAccountPerson,
} from "./support/in-memory-account-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { emptyModuleConfiguration } from "./support/in-memory-module-configuration.js";
import {
createInMemoryModuleLifecycleStore,
moduleLifecycleSnapshotFor,
} from "./support/in-memory-module-lifecycle.js";
import { emptyModuleStorage } from "./support/in-memory-module-storage.js";
import { readyHealth } from "./support/ready-health.js";
/**
* `GET /api/v1/account` and `PATCH /api/v1/account/preferences` (ADR 0062): a signed-in person's
* own account and preferences, self-only by construction.
*/
const trustedOrigin = "https://dashboard.example.test";
const adaId = parseEkklesiaUserId("11111111-1111-4111-8111-111111111111");
const graceId = parseEkklesiaUserId("22222222-2222-4222-8222-222222222222");
const ada = createAuthenticatedPrincipal(adaId);
const people: readonly InMemoryAccountPerson[] = [
{ email: "[email protected]", name: "Ada Lovelace", userId: adaId },
{
email: "[email protected]",
name: "Grace Hopper",
preferences: { appearance: "light", motion: "reduce" },
userId: graceId,
},
];
interface Options {
readonly principal?: EkklesiaPrincipal;
readonly evaluationFails?: boolean;
}
function build(options: Options = {}) {
const evaluator = createAuthorizationEvaluator({
grants: { hasActiveGrant: async () => false },
platformOwners: {
isPlatformOwner: async () => {
if (options.evaluationFails) {
throw new Error("database down");
}
return false;
},
},
});
const runtime: EkklesiaIdentityRuntime = {
handleAuthRequest: vi.fn(),
resolvePrincipal: vi.fn().mockResolvedValue(options.principal ?? ada),
};
const account = createInMemoryAccountStore(people);
const app = createApiApp({
account,
authorization: {
evaluator,
registry: composePlatformPermissionRegistry([]),
store: {} as unknown as AuthorizationStore,
},
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
moduleConfiguration: emptyModuleConfiguration(),
moduleLifecycle: {
snapshot: moduleLifecycleSnapshotFor([], { modules: [] }),
store: createInMemoryModuleLifecycleStore(),
},
moduleRealtime: EMPTY_MODULE_REALTIME_REGISTRY,
moduleRoutes: Object.freeze([]),
moduleServices: Object.freeze({
database: Object.freeze({}) as unknown as ModuleDatabase,
}) as LegacyModuleRuntimeServices,
moduleStorage: emptyModuleStorage(),
moduleUi: createModuleUiPublicationRegistry([]),
runtime,
trustedOrigins: [trustedOrigin],
});
return { account, app };
}
function patch(body: unknown, init: { origin?: string | null; raw?: string } = {}): RequestInit {
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (init.origin !== null) {
headers.Origin = init.origin ?? trustedOrigin;
}
return { body: init.raw ?? JSON.stringify(body), headers, method: "PATCH" };
}
describe("core.account.self.manage", () => {
it("is an authenticated-baseline Core permission, so managing your own account needs no grant", () => {
expect(CORE_PERMISSION_REGISTRY.get(CORE_ACCOUNT_SELF_MANAGE)?.baseline).toBe("authenticated");
});
it("holds Core's preference values equal to the design tokens' own", () => {
expect([...ACCOUNT_APPEARANCES]).toEqual([...EKKLESIA_APPEARANCES]);
expect([...ACCOUNT_MOTION_PREFERENCES]).toEqual([...EKKLESIA_MOTION_PREFERENCES]);
});
});
describe("GET /api/v1/account", () => {
it("returns the signed-in person's own name, email, and default preferences", async () => {
const { app } = build();
const response = await app.request(ACCOUNT_PATH);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("vary")).toContain("Cookie");
expect(await response.json()).toEqual({
email: "[email protected]",
name: "Ada Lovelace",
preferences: { appearance: "system", motion: "system" },
});
});
it("returns exactly name, email, and preferences — nothing else about the account", async () => {
const { app } = build();
const body = (await (await app.request(ACCOUNT_PATH)).json()) as Record<string, unknown>;
expect(Object.keys(body).sort()).toEqual(["email", "name", "preferences"]);
expect(Object.keys(body.preferences as object).sort()).toEqual(["appearance", "motion"]);
});
it("refuses an anonymous caller", async () => {
const { account, app } = build({ principal: ANONYMOUS_PRINCIPAL });
const response = await app.request(ACCOUNT_PATH);
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ code: "AUTHORIZATION_DENIED" });
expect(account.requestedUserIds).toEqual([]);
});
it("refuses a paired display device, which has no account", async () => {
const { account, app } = build({
principal: createDevicePrincipal("33333333-3333-4333-8333-333333333333"),
});
const response = await app.request(ACCOUNT_PATH);
expect(response.status).toBe(403);
expect(account.requestedUserIds).toEqual([]);
});
it("reads only the session's account, whatever the request names", async () => {
const { account, app } = build();
const response = await app.request(`${ACCOUNT_PATH}?userId=${graceId}&id=${graceId}`, {
headers: { "X-User-Id": graceId },
});
expect(((await response.json()) as { name: string }).name).toBe("Ada Lovelace");
expect(account.requestedUserIds).toEqual([adaId]);
});
it("has no route that addresses another person's account", async () => {
const { account, app } = build();
for (const path of [`${ACCOUNT_PATH}/${graceId}`, `${ACCOUNT_PREFERENCES_PATH}/${graceId}`]) {
expect((await app.request(path)).status).toBe(404);
expect((await app.request(path, patch({ appearance: "dark" }))).status).toBe(404);
}
expect(account.requestedUserIds).toEqual([]);
});
it("is not found when the session's person no longer exists", async () => {
const { app } = build({
principal: createAuthenticatedPrincipal("99999999-9999-4999-8999-999999999999"),
});
const response = await app.request(ACCOUNT_PATH);
expect(response.status).toBe(404);
expect(await response.json()).toEqual({ code: "ACCOUNT_NOT_FOUND" });
});
it("reports a storage failure as a sanitized 503", async () => {
const { account, app } = build();
account.failWith("ACCOUNT_READ_FAILED");
const response = await app.request(ACCOUNT_PATH);
expect(response.status).toBe(503);
expect(await response.json()).toEqual({ code: "ACCOUNT_READ_FAILED" });
});
it("reports an authorization outage as a 503, never as a denial", async () => {
// The authenticated baseline needs no owner lookup, so an owner-lookup outage cannot deny it.
const { app } = build({ evaluationFails: true });
expect((await app.request(ACCOUNT_PATH)).status).toBe(200);
});
});
describe("PATCH /api/v1/account/preferences", () => {
it.each([
["appearance", "light"],
["appearance", "dark"],
["appearance", "system"],
["motion", "reduce"],
["motion", "allow"],
["motion", "system"],
] as const)("saves %s %s and returns everything in effect", async (name, value) => {
const { app } = build();
const response = await app.request(ACCOUNT_PREFERENCES_PATH, patch({ [name]: value }));
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
const body = (await response.json()) as Record<string, string>;
expect(body[name]).toBe(value);
expect(Object.keys(body).sort()).toEqual(["appearance", "motion"]);
const read = (await (await app.request(ACCOUNT_PATH)).json()) as {
preferences: Record<string, string>;
};
expect(read.preferences[name]).toBe(value);
});
it("changes only the preference named", async () => {
const { app } = build();
await app.request(ACCOUNT_PREFERENCES_PATH, patch({ appearance: "dark" }));
const response = await app.request(ACCOUNT_PREFERENCES_PATH, patch({ motion: "reduce" }));
expect(await response.json()).toEqual({ appearance: "dark", motion: "reduce" });
});
it.each([
["an empty object", {}],
["an unknown appearance", { appearance: "sepia" }],
["an unknown motion", { motion: "none" }],
["an unknown key", { appearance: "dark", radius: "large" }],
["another person's id", { appearance: "dark", userId: "22222222-2222-4222-8222-222222222222" }],
["an array", ["dark"]],
["null", null],
])("refuses %s with nothing changed", async (_label, body) => {
const { account, app } = build();
const response = await app.request(ACCOUNT_PREFERENCES_PATH, patch(body));
expect(response.status).toBe(400);
expect(await response.json()).toEqual({ code: "INVALID_REQUEST" });
expect(account.requestedUserIds).toEqual([]);
});
it("refuses a body that is not JSON", async () => {
const { app } = build();
const response = await app.request(ACCOUNT_PREFERENCES_PATH, patch(undefined, { raw: "{" }));
expect(response.status).toBe(400);
});
it("refuses an untrusted or missing Origin before anything else", async () => {
const { account, app } = build();
for (const origin of ["https://elsewhere.example.test", null] as const) {
const response = await app.request(
ACCOUNT_PREFERENCES_PATH,
patch({ appearance: "dark" }, { origin }),
);
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ code: "UNTRUSTED_ORIGIN" });
}
expect(account.requestedUserIds).toEqual([]);
});
it("refuses an oversized body", async () => {
const { app } = build();
const response = await app.request(
ACCOUNT_PREFERENCES_PATH,
patch(undefined, { raw: JSON.stringify({ appearance: "dark", pad: "x".repeat(20_000) }) }),
);
expect(response.status).toBe(413);
});
it("refuses an anonymous caller and a device", async () => {
for (const principal of [
ANONYMOUS_PRINCIPAL,
createDevicePrincipal("33333333-3333-4333-8333-333333333333"),
]) {
const { account, app } = build({ principal });
const response = await app.request(ACCOUNT_PREFERENCES_PATH, patch({ appearance: "dark" }));
expect(response.status).toBe(403);
expect(account.requestedUserIds).toEqual([]);
}
});
it("changes only the session's own preferences, never another person's", async () => {
const { account, app } = build();
await app.request(
`${ACCOUNT_PREFERENCES_PATH}?userId=${graceId}`,
patch({ appearance: "dark", motion: "allow" }),
);
expect(account.requestedUserIds).toEqual([adaId]);
expect((await account.readAccount(graceId))?.preferences).toEqual({
appearance: "light",
motion: "reduce",
});
});
it("reports a storage failure as a sanitized 503", async () => {
const { account, app } = build();
account.failWith("ACCOUNT_WRITE_FAILED");
const response = await app.request(ACCOUNT_PREFERENCES_PATH, patch({ appearance: "dark" }));
expect(response.status).toBe(503);
expect(await response.json()).toEqual({ code: "ACCOUNT_WRITE_FAILED" });
});
it("answers a preflight from the Dashboard origin with PATCH allowed", async () => {
const { app } = build();
const response = await app.request(ACCOUNT_PREFERENCES_PATH, {
headers: {
"Access-Control-Request-Method": "PATCH",
Origin: trustedOrigin,
},
method: "OPTIONS",
});
expect(response.headers.get("access-control-allow-origin")).toBe(trustedOrigin);
expect(response.headers.get("access-control-allow-methods")).toContain("PATCH");
});
});
+161 -3
View File
@@ -260,6 +260,7 @@ async function applyCoreMigrations(url: string): Promise<void> {
"core:0005_module_configuration",
"core:0006_device_identity",
"core:0007_verified_bootstrap_owners",
"core:0008_user_preferences",
]);
expect(aggregate.migrations[0]?.checksum).toBe(
"f8f2086ef06f7a6943e8ffc4350bb010b37aed04c0a72030d2b153c986b1325f",
@@ -1521,6 +1522,162 @@ describe.sequential("live API — exported browser auth shell against PostgreSQL
});
});
describe.sequential("live API — a person's own account and preferences (ADR 0062)", () => {
let database: { name: string; url: string };
let running: RunningApi;
let origin: string;
let ada: { cookie: string; userId: string };
let grace: { cookie: string; userId: string };
const password = "correct horse battery staple";
async function account(cookie?: string): Promise<{ status: number; body: unknown }> {
const response = await fetch(`${origin}/api/v1/account`, {
headers: { origin: dashboardOrigin, ...(cookie ? { cookie } : {}) },
});
return { body: await response.json(), status: response.status };
}
async function changePreferences(
cookie: string | undefined,
body: unknown,
options: { readonly origin?: string; readonly query?: string } = {},
): Promise<{ status: number; body: unknown }> {
const response = await fetch(`${origin}/api/v1/account/preferences${options.query ?? ""}`, {
body: JSON.stringify(body),
headers: {
"content-type": "application/json",
origin: options.origin ?? dashboardOrigin,
...(cookie ? { cookie } : {}),
},
method: "PATCH",
});
return { body: await response.json(), status: response.status };
}
async function person(email: string): Promise<{ cookie: string; userId: string }> {
const created = await signUp(origin, email, password);
expect(created.response.status).toBe(200);
const session = await signIn(origin, email, password);
if (!session.cookiePair) {
throw harnessError("The account session cookie was not issued.");
}
return { cookie: session.cookiePair, userId: created.body.user.id };
}
it("starts a freshly migrated API with two ordinary accounts", async () => {
database = await createDisposableDatabase("account_prefs");
await applyCoreMigrations(database.url);
running = await startMigratedApi(database.url);
origin = apiOrigin(running);
ada = await person("[email protected]");
grace = await person("[email protected]");
});
it("shows each person their own name, email, and the defaults, with no grant", async () => {
expect(await account(ada.cookie)).toEqual({
body: {
email: "[email protected]",
name: "Integration Test User",
preferences: { appearance: "system", motion: "system" },
},
status: 200,
});
expect(((await account(grace.cookie)).body as { email: string }).email).toBe(
"[email protected]",
);
});
it("refuses an anonymous caller both routes", async () => {
expect((await account()).status).toBe(403);
expect((await changePreferences(undefined, { appearance: "dark" })).status).toBe(403);
});
it("saves each person's change to their own account only", async () => {
expect(await changePreferences(ada.cookie, { appearance: "dark" })).toEqual({
body: { appearance: "dark", motion: "system" },
status: 200,
});
expect(await changePreferences(ada.cookie, { motion: "reduce" })).toEqual({
body: { appearance: "dark", motion: "reduce" },
status: 200,
});
expect((await account(grace.cookie)).body).toMatchObject({
preferences: { appearance: "system", motion: "system" },
});
});
it("cannot be pointed at another person's account by the query or the body", async () => {
const viaQuery = await changePreferences(
ada.cookie,
{ appearance: "light" },
{ query: `?userId=${grace.userId}` },
);
expect(viaQuery).toEqual({ body: { appearance: "light", motion: "reduce" }, status: 200 });
const viaBody = await changePreferences(ada.cookie, {
appearance: "dark",
userId: grace.userId,
});
expect(viaBody).toEqual({ body: { code: "INVALID_REQUEST" }, status: 400 });
expect((await account(grace.cookie)).body).toMatchObject({
preferences: { appearance: "system", motion: "system" },
});
expect((await account(ada.cookie)).body).toMatchObject({
preferences: { appearance: "light", motion: "reduce" },
});
});
it("refuses an untrusted Origin and an invalid value, changing nothing", async () => {
expect(
await changePreferences(ada.cookie, { appearance: "dark" }, { origin: untrustedOrigin }),
).toEqual({ body: { code: "UNTRUSTED_ORIGIN" }, status: 403 });
expect(await changePreferences(ada.cookie, { appearance: "sepia" })).toEqual({
body: { code: "INVALID_REQUEST" },
status: 400,
});
expect((await account(ada.cookie)).body).toMatchObject({
preferences: { appearance: "light", motion: "reduce" },
});
});
it("follows the person to a new session, as another device would see it", async () => {
const elsewhere = await signIn(origin, "[email protected]", password);
expect((await account(elsewhere.cookiePair as string)).body).toMatchObject({
preferences: { appearance: "light", motion: "reduce" },
});
});
it("stores exactly one typed row, for the one person who chose something", async () => {
const admin = await openAdministrativeClient(database.url);
try {
const rows = await safeQuery<{ user_id: string; appearance: string; motion: string }>(
admin,
"select user_id, appearance, motion from ekklesia_core_user_preference",
);
expect(rows).toEqual([{ appearance: "light", motion: "reduce", user_id: ada.userId }]);
} finally {
await safeEnd(admin);
}
});
it("refuses a signed-out session", async () => {
const signedOut = await fetch(`${origin}/api/auth/sign-out`, {
body: "{}",
headers: { "content-type": "application/json", cookie: ada.cookie, origin: dashboardOrigin },
method: "POST",
});
expect(signedOut.status).toBe(200);
expect((await account(ada.cookie)).status).toBe(403);
expect((await changePreferences(ada.cookie, { appearance: "dark" })).status).toBe(403);
});
it("shuts down cleanly", async () => {
await running.shutdown();
await dropDatabase(database.name);
});
});
describe.sequential("live API — startup and migration guarantees", () => {
it("refuses to start against an unmigrated database, and creates no tables or migration history", async () => {
const database = await createDisposableDatabase("unmigrated");
@@ -2630,10 +2787,11 @@ 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 six (`core.authorization.grants.manage`, `core.modules.ui.read`,
// Core's own seven (`core.authorization.grants.manage`, `core.modules.ui.read`,
// `core.dashboard.navigation.manage`, `core.modules.lifecycle.manage`,
// `core.modules.configuration.manage`, `core.devices.manage`) plus the fixture module's one.
details: ["7 permissions registered"],
// `core.modules.configuration.manage`, `core.devices.manage`, `core.account.self.manage`)
// plus the fixture module's one.
details: ["8 permissions registered"],
status: "pass",
});
// Doctor and permission composition read only the manifest — the fixture's register/start
+24
View File
@@ -30,6 +30,7 @@ import {
createApiApp as createApiAppWithModules,
} from "../src/app.js";
import { AUTH_REQUEST_MAX_BODY_BYTES } from "../src/body-limits.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { readyHealth } from "./support/ready-health.js";
@@ -111,6 +112,7 @@ function createAuthWiringApp(runtime: EkklesiaIdentityRuntime) {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -130,6 +132,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -366,6 +369,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -391,6 +395,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -418,6 +423,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -447,6 +453,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -476,6 +483,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -502,6 +510,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -530,6 +539,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -555,6 +565,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -582,6 +593,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -616,6 +628,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -651,6 +664,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -691,6 +705,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -713,6 +728,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -737,6 +753,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -760,6 +777,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -781,6 +799,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -809,6 +828,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -840,6 +860,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -874,6 +895,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -899,6 +921,7 @@ describe("Ekklesia API Hono application", () => {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -938,6 +961,7 @@ describe("split Dashboard and API origins (ADR 0045)", () => {
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
moduleRealtime,
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
+34 -8
View File
@@ -8,6 +8,7 @@ vi.mock("@ekklesia/shell/dashboard-assets", () => ({
dashboardHostAssetUrls: Object.freeze({
html: "file:///surface/browser/index.html",
script: "file:///surface/browser/assets/ekklesia-dashboard/app.js",
appearance: "file:///surface/browser/assets/ekklesia-dashboard/appearance.js",
}),
}));
@@ -28,19 +29,26 @@ function sha256Etag(text: string): string {
describe("Dashboard host asset loading", () => {
beforeEach(() => readFileMock.mockReset());
it("reads only the two declared file URLs in order and freezes one consistent snapshot", async () => {
it("reads only the three declared file URLs in order and freezes one consistent snapshot", async () => {
const html = `<!doctype html>${DASHBOARD_API_ORIGIN_PLACEHOLDER}<div id="ekklesia-host"></div>`;
const script = "export const dashboardHost = true;\n";
readFileMock.mockResolvedValueOnce(html).mockResolvedValueOnce(script);
const appearanceScript = "(() => {})();\n";
readFileMock
.mockResolvedValueOnce(html)
.mockResolvedValueOnce(script)
.mockResolvedValueOnce(appearanceScript);
const assets = await loadDashboardHostAssets(API_ORIGIN);
expect(readFileMock.mock.calls).toEqual([
[new URL("file:///surface/browser/index.html"), "utf8"],
[new URL("file:///surface/browser/assets/ekklesia-dashboard/app.js"), "utf8"],
[new URL("file:///surface/browser/assets/ekklesia-dashboard/appearance.js"), "utf8"],
]);
const rendered = `<!doctype html><meta content="${API_ORIGIN}" name="ekklesia-api-origin" /><div id="ekklesia-host"></div>`;
expect(assets).toEqual({
appearanceScript,
appearanceScriptEtag: sha256Etag(appearanceScript),
html: rendered,
htmlEtag: sha256Etag(rendered),
script,
@@ -83,12 +91,27 @@ describe("Dashboard host asset loading", () => {
expect(readFileMock).toHaveBeenCalledTimes(2);
});
it("rejects an empty page or script as an unavailable shell build", () => {
for (const [html, script] of [
["", "export {};"],
["<html></html>", " \n"],
it("fails when the appearance script is missing even though the page and script were read", async () => {
readFileMock
.mockResolvedValueOnce(`<!doctype html>${DASHBOARD_API_ORIGIN_PLACEHOLDER}`)
.mockResolvedValueOnce("export {};\n")
.mockRejectedValueOnce(new Error("ENOENT appearance.js"));
await expect(loadDashboardHostAssets(API_ORIGIN)).rejects.toBeInstanceOf(
DashboardHostAssetError,
);
expect(readFileMock).toHaveBeenCalledTimes(3);
});
it("rejects an empty page, script, or appearance script as an unavailable shell build", () => {
for (const [html, script, appearance] of [
["", "export {};", "(() => {})();"],
["<html></html>", " \n", "(() => {})();"],
["<html></html>", "export {};", " "],
] as const) {
expect(() => createDashboardHostAssets(html, script)).toThrow(DashboardHostAssetError);
expect(() => createDashboardHostAssets(html, script, appearance)).toThrow(
DashboardHostAssetError,
);
}
});
@@ -99,7 +122,10 @@ describe("Dashboard host asset loading", () => {
'<!doctype html><meta content="https://elsewhere.test" name="ekklesia-api-origin" />',
]) {
readFileMock.mockReset();
readFileMock.mockResolvedValueOnce(html).mockResolvedValueOnce("export {};\n");
readFileMock
.mockResolvedValueOnce(html)
.mockResolvedValueOnce("export {};\n")
.mockResolvedValueOnce("(() => {})();\n");
await expect(loadDashboardHostAssets(API_ORIGIN)).rejects.toBeInstanceOf(
DashboardHostAssetError,
);
+64 -5
View File
@@ -38,6 +38,7 @@ import {
} from "../src/dashboard-host-assets.js";
import {
DASHBOARD_HOST_PAGE_PATH,
DASHBOARD_HOST_APPEARANCE_SCRIPT_PATH,
DASHBOARD_HOST_SCRIPT_PATH,
DashboardHostConfigurationError,
createDashboardHostRoutes,
@@ -51,6 +52,7 @@ import {
DISPLAY_HOST_SCRIPT_PATH,
DISPLAY_SERVICE_WORKER_PATH,
} from "../src/module-display-routes.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { emptyModuleConfiguration } from "./support/in-memory-module-configuration.js";
import {
@@ -73,6 +75,8 @@ function sha256Etag(text: string): string {
const PAGE_ETAG = sha256Etag(PAGE_HTML);
const SCRIPT_ETAG = sha256Etag(SCRIPT);
const APPEARANCE_SCRIPT = "(() => { /* pre-paint appearance */ })();\n";
const APPEARANCE_SCRIPT_ETAG = sha256Etag(APPEARANCE_SCRIPT);
function fakeRuntime(): EkklesiaIdentityRuntime {
return {
@@ -156,8 +160,10 @@ function buildApp(
},
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: options.assets ?? createDashboardHostAssets(PAGE_HTML, SCRIPT),
dashboardHostAssets:
options.assets ?? createDashboardHostAssets(PAGE_HTML, SCRIPT, APPEARANCE_SCRIPT),
health: readyHealth(),
runtime,
trustedOrigins: [trustedOrigin],
@@ -357,7 +363,10 @@ describe("Dashboard deep links (ADR 0057)", () => {
for (const modulePages of [["api"], ["settings"], ["display"], ["Not-An-Id"], ["a", "a"]]) {
expect(
() =>
createDashboardHostRoutes(createDashboardHostAssets(PAGE_HTML, SCRIPT), { modulePages }),
createDashboardHostRoutes(
createDashboardHostAssets(PAGE_HTML, SCRIPT, APPEARANCE_SCRIPT),
{ modulePages },
),
JSON.stringify(modulePages),
).toThrow(DashboardHostConfigurationError);
}
@@ -457,8 +466,45 @@ describe("GET /assets/ekklesia-dashboard/app.js (the Dashboard script)", () => {
});
});
describe("GET /assets/ekklesia-dashboard/appearance.js (the pre-paint appearance script)", () => {
it("serves the exact pre-paint script as JavaScript with revalidation and its own strong ETag", async () => {
const { app } = buildApp();
const response = await app.request(DASHBOARD_HOST_APPEARANCE_SCRIPT_PATH);
expect(response.status).toBe(200);
expect(await response.text()).toBe(APPEARANCE_SCRIPT);
expect(response.headers.get("content-type")).toBe("text/javascript; charset=utf-8");
expect(response.headers.get("cache-control")).toBe("no-cache");
expect(response.headers.get("etag")).toBe(APPEARANCE_SCRIPT_ETAG);
expect(response.headers.get("x-content-type-options")).toBe("nosniff");
// Code only: nothing about any viewer, and nothing that varies by request.
expect(response.headers.get("set-cookie")).toBeNull();
expect(response.headers.get("vary")).toBeNull();
});
it("answers a matching If-None-Match with a 304, and does not accept the app script's validator", async () => {
const { app } = buildApp();
const notModified = await app.request(DASHBOARD_HOST_APPEARANCE_SCRIPT_PATH, {
headers: { "If-None-Match": APPEARANCE_SCRIPT_ETAG },
});
expect(notModified.status).toBe(304);
expect(notModified.headers.get("etag")).toBe(APPEARANCE_SCRIPT_ETAG);
const other = await app.request(DASHBOARD_HOST_APPEARANCE_SCRIPT_PATH, {
headers: { "If-None-Match": SCRIPT_ETAG },
});
expect(other.status).toBe(200);
});
it("lives beside the app script, in the Dashboard's own asset namespace", () => {
expect(DASHBOARD_HOST_APPEARANCE_SCRIPT_PATH).toBe("/assets/ekklesia-dashboard/appearance.js");
});
});
describe("Dashboard host boundaries", () => {
it("serves nothing but its two exact paths, answering every other spelling with the sanitized 404", async () => {
it("serves nothing but its exact paths, answering every other spelling with the sanitized 404", async () => {
const { app } = buildApp();
for (const path of [
@@ -472,6 +518,10 @@ describe("Dashboard host boundaries", () => {
"/assets/ekklesia-dashboard/index.html",
"/assets/",
"/assets/ekklesia-dashboard/APP.JS",
"/assets/ekklesia-dashboard/appearance.js.map",
"/assets/ekklesia-dashboard/appearance.js/",
"/assets/ekklesia-dashboard/APPEARANCE.JS",
"/appearance.js",
"/dashboard",
"/login",
]) {
@@ -560,12 +610,21 @@ describe("Dashboard host boundaries", () => {
});
it("refuses at composition a snapshot whose validator does not match its bytes, or empty bytes", () => {
const consistent = createDashboardHostAssets(PAGE_HTML, SCRIPT);
const consistent = createDashboardHostAssets(PAGE_HTML, SCRIPT, APPEARANCE_SCRIPT);
for (const assets of [
{ ...consistent, html: `${PAGE_HTML}<!-- tampered -->` },
{ ...consistent, scriptEtag: PAGE_ETAG },
{ html: "", htmlEtag: sha256Etag(""), script: SCRIPT, scriptEtag: SCRIPT_ETAG },
{ ...consistent, appearanceScriptEtag: SCRIPT_ETAG },
{ ...consistent, appearanceScript: `${APPEARANCE_SCRIPT}// tampered` },
{
appearanceScript: APPEARANCE_SCRIPT,
appearanceScriptEtag: APPEARANCE_SCRIPT_ETAG,
html: "",
htmlEtag: sha256Etag(""),
script: SCRIPT,
scriptEtag: SCRIPT_ETAG,
},
]) {
expect(() => buildApp({ assets })).toThrow(DashboardHostConfigurationError);
}
+2
View File
@@ -26,6 +26,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { createApiApp } from "../src/app.js";
import { DASHBOARD_NAVIGATION_PATH } from "../src/dashboard-routes.js";
import { MODULE_UI_INVENTORY_PATH } from "../src/module-ui-inventory.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { readyHealth } from "./support/ready-health.js";
@@ -140,6 +141,7 @@ async function install(options: InstallOptions = {}): Promise<{ app: Hono }> {
const app = createApiApp({
authorization: { evaluator, registry: composePlatformPermissionRegistry(modules), store },
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(options.configuration ?? {}),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -28,6 +28,7 @@ import {
DASHBOARD_SETTINGS_PATH,
type DashboardSettingsResponse,
} from "../src/dashboard-settings-routes.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { emptyModuleConfiguration } from "./support/in-memory-module-configuration.js";
@@ -127,6 +128,7 @@ function build(options: Options = {}) {
} as unknown as AuthorizationStore;
const app = createApiApp({
authorization: { evaluator, registry: composePlatformPermissionRegistry(modules), store },
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
+2
View File
@@ -24,6 +24,7 @@ import {
HEALTH_READY_PATH,
READINESS_DATABASE_TIMEOUT_MS,
} from "../src/health-routes.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { emptyModuleConfiguration } from "./support/in-memory-module-configuration.js";
@@ -91,6 +92,7 @@ function buildApp(
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health,
+1 -1
View File
@@ -20,7 +20,7 @@ vi.mock("@hono/node-server", () => ({ serve: serveMock }));
vi.mock("../src/dashboard-host-assets.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../src/dashboard-host-assets.js")>();
loadDashboardHostAssetsMock.mockImplementation(async () =>
actual.createDashboardHostAssets("<!doctype html>", "export {};\n"),
actual.createDashboardHostAssets("<!doctype html>", "export {};\n", "(() => {})();\n"),
);
return { ...actual, loadDashboardHostAssets: loadDashboardHostAssetsMock };
});
@@ -34,6 +34,7 @@ import { createApiApp } from "../src/app.js";
import { CORE_MUTATION_MAX_BODY_BYTES } from "../src/body-limits.js";
import { MODULE_CONFIGURATION_PATH } from "../src/module-configuration-routes.js";
import { MODULE_LIFECYCLE_PATH } from "../src/module-lifecycle-routes.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { readyHealth } from "./support/ready-health.js";
@@ -190,6 +191,7 @@ async function install(options: InstallOptions = {}): Promise<Installation> {
registry: composePlatformPermissionRegistry(modules),
store: authorizationStore,
},
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -249,6 +249,7 @@ async function applyCoreMigrations(url: string): Promise<void> {
"core:0005_module_configuration",
"core:0006_device_identity",
"core:0007_verified_bootstrap_owners",
"core:0008_user_preferences",
]);
await applyModuleMigrations({ aggregate, database: createPostgresMigrationDatabase(url) });
} finally {
@@ -279,6 +280,7 @@ async function applyMigrationsWithModule(url: string): Promise<void> {
"core:0005_module_configuration",
"core:0006_device_identity",
"core:0007_verified_bootstrap_owners",
"core:0008_user_preferences",
"db-facade:0000_initial",
]);
expect(aggregate.migrations[0]?.checksum).toBe(
@@ -37,6 +37,7 @@ import { moduleApiBaseUrl } from "../src/module-http-routes.js";
import { moduleRealtimeBaseUrl } from "../src/module-realtime-routes.js";
import { MODULE_UI_INVENTORY_PATH } from "../src/module-ui-inventory.js";
import { moduleDisplayUiArtifactUrl } from "../src/module-ui-routes.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { readyHealth } from "./support/ready-health.js";
@@ -199,6 +200,7 @@ async function install(options: InstallOptions): Promise<Installation> {
registry: composePlatformPermissionRegistry(modules),
store: fakeAuthorizationStore(),
},
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -30,6 +30,7 @@ import {
mergedVaryHeader,
} from "../src/module-http-routes.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { emptyModuleConfiguration } from "./support/in-memory-module-configuration.js";
import { emptyModuleLifecycle } from "./support/in-memory-module-lifecycle.js";
@@ -125,6 +126,7 @@ function buildModuleApp(options: {
moduleLifecycle: emptyModuleLifecycle(),
moduleConfiguration: emptyModuleConfiguration(),
moduleStorage: emptyModuleStorage(),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -32,6 +32,7 @@ import { DASHBOARD_NAVIGATION_PATH } from "../src/dashboard-routes.js";
import { CORE_MUTATION_MAX_BODY_BYTES } from "../src/body-limits.js";
import { MODULE_LIFECYCLE_PATH } from "../src/module-lifecycle-routes.js";
import { MODULE_UI_INVENTORY_PATH } from "../src/module-ui-inventory.js";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { readyHealth } from "./support/ready-health.js";
@@ -172,6 +173,7 @@ async function install(options: InstallOptions = {}): Promise<Installation> {
registry: composePlatformPermissionRegistry(modules),
store: authorizationStore,
},
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
+42 -1
View File
@@ -33,8 +33,10 @@ import {
createModuleUiContext,
type EkklesiaHostConfig,
moduleUiSourceUrl,
saveHostAccountPreferences,
} from "@ekklesia/shell";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { readyHealth } from "./support/ready-health.js";
@@ -216,6 +218,8 @@ interface HarnessOptions {
* single module proves very little. */
readonly extraModules?: ReadonlyArray<{ readonly id: string; readonly name: string }>;
readonly platformOwner?: boolean;
/** People with an account, for the account area's routes (ADR 0062). */
readonly people?: Parameters<typeof createInMemoryAccountStore>[0];
}
interface Harness {
@@ -289,6 +293,7 @@ async function startHarness(options: HarnessOptions = {}): Promise<Harness> {
},
moduleConfiguration: moduleConfigurationOptionFor(modules),
moduleStorage: moduleStorageOptionFor(modules),
account: createInMemoryAccountStore(options.people ?? []),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -302,7 +307,10 @@ async function startHarness(options: HarnessOptions = {}): Promise<Harness> {
if (url.pathname.startsWith("/api/v1/modules/")) {
moduleApiCalls.push(`${init?.method ?? "GET"} ${url.pathname}${url.search}`);
}
return app.request(url.href, init);
// A browser names the Dashboard's origin on every cross-origin request; the shell never sets it.
const headers = new Headers(init?.headers);
headers.set("Origin", "https://dashboard.example.test");
return app.request(url.href, { ...init, headers });
}) as unknown as typeof fetch;
return {
@@ -738,6 +746,39 @@ describe("end to end: a discovered module's UI mounts in the Ekklesia host", ()
}
});
it("loads the signed-in person's own account, and a saved preference is what the next load sees (ADR 0062)", async () => {
const harness = await startHarness({
people: [{ email: "[email protected]", name: "Viewer Person", userId: viewerId }],
principal: createAuthenticatedPrincipal(viewerId),
});
try {
const first = await bootstrapHost(harness.config);
expect(first.account).toEqual({
email: "[email protected]",
name: "Viewer Person",
preferences: { appearance: "system", motion: "system" },
});
expect(await saveHostAccountPreferences(harness.config, { appearance: "dark" })).toEqual({
appearance: "dark",
motion: "system",
});
expect(await saveHostAccountPreferences(harness.config, { motion: "reduce" })).toEqual({
appearance: "dark",
motion: "reduce",
});
// Another device signing in reads the account, not this one's browser.
const next = await bootstrapHost(harness.config);
expect(next.account !== "unavailable" && next.account.preferences).toEqual({
appearance: "dark",
motion: "reduce",
});
} finally {
await harness.stop();
}
});
it("gives an anonymous visitor no inventory and therefore nothing to mount", async () => {
const harness = await startHarness();
try {
@@ -24,6 +24,7 @@ import {
} from "@ekklesia/core/modules";
import type { Hono } from "hono";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { readyHealth } from "./support/ready-health.js";
@@ -209,6 +210,7 @@ async function install(options: InstallOptions): Promise<Installation> {
},
moduleConfiguration: moduleConfigurationOptionFor(modules),
moduleStorage: moduleStorageOptionFor(modules),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
+2
View File
@@ -18,6 +18,7 @@ import { MODULE_UI_ABI_VERSION, NO_MODULE_UI_CONTRIBUTIONS } from "@ekklesia/mod
import { Window } from "happy-dom";
import type { Hono } from "hono";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createInMemoryAccountStore } from "./support/in-memory-account-store.js";
import { createInMemoryDashboardStore } from "./support/in-memory-dashboard-store.js";
import { testDashboardHostAssets } from "./support/dashboard-host-assets.js";
import { readyHealth } from "./support/ready-health.js";
@@ -254,6 +255,7 @@ async function install(
},
moduleConfiguration: moduleConfigurationOptionFor(modules),
moduleStorage: moduleStorageOptionFor(modules),
account: createInMemoryAccountStore(),
dashboard: createInMemoryDashboardStore(),
dashboardHostAssets: testDashboardHostAssets(),
health: readyHealth(),
@@ -9,5 +9,6 @@ export function testDashboardHostAssets(): DashboardHostAssets {
return createDashboardHostAssets(
'<!doctype html><div id="ekklesia-host"></div><script src="/assets/ekklesia-dashboard/app.js" type="module"></script>',
"export const dashboardHost = true;\n",
"(() => {})();\n",
);
}
@@ -0,0 +1,85 @@
import type { EkklesiaUserId } from "@ekklesia/contracts";
import {
type AccountPreferences,
type AccountPreferencesUpdate,
type AccountStore,
AccountStoreError,
type AccountSummary,
DEFAULT_ACCOUNT_PREFERENCES,
parseAccountPreferencesUpdate,
} from "@ekklesia/core/account";
export interface InMemoryAccountPerson {
readonly userId: string;
readonly name: string;
readonly email: string;
readonly preferences?: Partial<AccountPreferences>;
}
export interface InMemoryAccountStore extends AccountStore {
/** Every user id a read or write was asked for, in order, so a route test can prove which account
* the route touched — the session's, and never one named by the request. */
readonly requestedUserIds: readonly string[];
/** Makes the next operations fail the way an unreachable database would. */
failWith(code: "ACCOUNT_READ_FAILED" | "ACCOUNT_WRITE_FAILED" | undefined): void;
}
/**
* An in-memory `AccountStore` for tests that exercise **routing and authorization**, not
* persistence. It reproduces the store's contract — strict update parsing, partial updates, an
* unknown person is not found — and nothing a database owns; persistence, the `CHECK`
* constraints, isolation across connections, and the cascade are proven against real PostgreSQL in
* `core/tests/account-store.integration.ts`.
*/
export function createInMemoryAccountStore(
people: readonly InMemoryAccountPerson[] = [],
): InMemoryAccountStore {
const records = new Map<string, { name: string; email: string; preferences: AccountPreferences }>(
people.map((person) => [
person.userId,
{
email: person.email,
name: person.name,
preferences: { ...DEFAULT_ACCOUNT_PREFERENCES, ...person.preferences },
},
]),
);
const requestedUserIds: string[] = [];
let failure: "ACCOUNT_READ_FAILED" | "ACCOUNT_WRITE_FAILED" | undefined;
return {
failWith(code) {
failure = code;
},
async readAccount(userId: EkklesiaUserId): Promise<AccountSummary | undefined> {
requestedUserIds.push(userId);
if (failure) {
throw new AccountStoreError("ACCOUNT_READ_FAILED");
}
const record = records.get(userId);
return record
? { email: record.email, name: record.name, preferences: { ...record.preferences } }
: undefined;
},
requestedUserIds,
async updatePreferences(
userId: EkklesiaUserId,
update: AccountPreferencesUpdate,
): Promise<AccountPreferences> {
requestedUserIds.push(userId);
const parsed = parseAccountPreferencesUpdate(update);
if (!parsed) {
throw new AccountStoreError("ACCOUNT_PREFERENCES_INVALID");
}
if (failure) {
throw new AccountStoreError("ACCOUNT_WRITE_FAILED");
}
const record = records.get(userId);
if (!record) {
throw new AccountStoreError("ACCOUNT_NOT_FOUND");
}
record.preferences = { ...record.preferences, ...parsed };
return { ...record.preferences };
},
};
}