Favourite pages that follow the user, and a narrow icon-only sidebar

A star beside each page in the sidebar pins it under "Favourites" at the top of
the menu; the list is saved with the user (users.favorites, migration 0020), so
it follows them to any browser, is offered first in the search box, and can be
changed from there too. A button at the foot of the sidebar, or the [ key,
narrows it to a strip of icons, where a group's pages open in a small menu
beside its icon and the alert and maintenance counts stay visible; the choice
is kept per browser and applies only on wide screens. Menu text on a coloured
(environment) sidebar is full strength for contrast, and menu badges sit in
line on a phone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-15 22:38:48 +02:00
1 parent 57fd4f8c52
commit 65263a64e3
17 files changed
+2736 -86

No files matched your search

+1
View File
@@ -0,0 +1 @@
ALTER TABLE `users` ADD `favorites` text;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -141,6 +141,13 @@
"when": 1792014514813,
"tag": "0019_complex_proudstar",
"breakpoints": true
},
{
"idx": 20,
"version": "6",
"when": 1792093015342,
"tag": "0020_salty_black_tom",
"breakpoints": true
}
]
}
+2
View File
@@ -16,6 +16,8 @@ export const users = sqliteTable("users", {
.notNull()
.default(sql`(current_timestamp)`),
lastLoginAt: text("last_login_at"),
// The pages this person pinned to the top of their menu, as a JSON array of paths ("/servers", "/alerts"). It follows them to any browser.
favorites: text("favorites"),
});
// ─── Audit log ──────────────────────────────────────────────────────────────
+38 -2
View File
@@ -1,9 +1,45 @@
import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { users } from "../db/schema.js";
import { requireAuth } from "../auth/middleware.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const meRouter = Router();
/** The most pages anyone can pin: enough for a working set, not a second menu. */
export const MAX_FAVORITES = 24;
/** What is stored, read back as a list. Anything that isn't one is no favourites rather than an error. */
export function parseFavorites(stored: string | null): string[] {
if (!stored) return [];
try {
const value = JSON.parse(stored);
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string").slice(0, MAX_FAVORITES) : [];
} catch {
return [];
}
}
meRouter.get("/", requireAuth, (req, res) => {
const { id, email, name, role, oidcSub } = req.currentUser!;
res.json({ user: { id, sub: oidcSub, email, name, role } });
const { id, email, name, role, oidcSub, favorites } = req.currentUser!;
res.json({ user: { id, sub: oidcSub, email, name, role, favorites: parseFavorites(favorites) } });
});
// Paths inside the app only: a slash, then letters, digits, dashes, underscores and further slashes. Which of them are real pages is
// the menu's business; a favourite for a page that is gone, or that this person's role can't open, is simply not shown.
const favoritesSchema = z.object({
paths: z.array(z.string().regex(/^\/[A-Za-z0-9\-_/]{0,80}$/, "Not a page path")).max(MAX_FAVORITES),
});
// Replaces the signed-in person's pinned pages. Only ever their own.
meRouter.put("/favorites", requireAuth, asyncHandler(async (req, res) => {
const parsed = favoritesSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "invalid_body", message: `Pin up to ${MAX_FAVORITES} pages, by their path.`, details: parsed.error.flatten() });
}
const paths = [...new Set(parsed.data.paths)];
await db.update(users).set({ favorites: JSON.stringify(paths) }).where(eq(users.id, req.currentUser!.id));
res.json({ favorites: paths });
}));
+117
View File
@@ -0,0 +1,117 @@
/**
* Pinned pages follow the person: stored on their user, read with /api/me, replaced with PUT /api/me/favorites, and only ever their own.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-favorites-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { meRouter, parseFavorites, MAX_FAVORITES } = await import("../src/routes/me.js");
await runMigrations();
describe("parseFavorites", () => {
test("a stored list reads back; anything else is an empty list", () => {
assert.deepEqual(parseFavorites('["/servers","/alerts"]'), ["/servers", "/alerts"]);
assert.deepEqual(parseFavorites(null), []);
assert.deepEqual(parseFavorites("not json"), []);
assert.deepEqual(parseFavorites('{"a":1}'), []);
assert.deepEqual(parseFavorites('["/ok", 5, null]'), ["/ok"]);
});
});
describe("/api/me favourites", () => {
let app: Server;
let base = "";
let who = "anna";
before(async () => {
await db.insert(users).values([
{ oidcSub: "anna", name: "Anna", role: "viewer" },
{ oidcSub: "bob", name: "Bob", role: "operator" },
]);
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
if (who) (req as unknown as { session: unknown }).session = { user: { sub: who } };
else (req as unknown as { session: unknown }).session = {};
next();
});
a.use("/api/me", meRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/me`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const put = (paths: unknown) =>
fetch(`${base}/favorites`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ paths }) });
const me = async () => (await (await fetch(base)).json()).user;
test("a new user has none", async () => {
assert.deepEqual((await me()).favorites, []);
});
test("a saved list comes back with the user, in order, with repeats removed", async () => {
const res = await put(["/servers", "/alerts", "/servers", "/settings/notifications"]);
assert.equal(res.status, 200);
assert.deepEqual((await res.json()).favorites, ["/servers", "/alerts", "/settings/notifications"]);
assert.deepEqual((await me()).favorites, ["/servers", "/alerts", "/settings/notifications"]);
});
test("it is replaced, not added to, and can be emptied", async () => {
await put(["/maintenance"]);
assert.deepEqual((await me()).favorites, ["/maintenance"]);
await put([]);
assert.deepEqual((await me()).favorites, []);
});
test("one person's list is not another's", async () => {
who = "anna";
await put(["/secrets"]);
who = "bob";
assert.deepEqual((await me()).favorites, []);
await put(["/dns"]);
who = "anna";
assert.deepEqual((await me()).favorites, ["/secrets"]);
});
test("anything that isn't an in-app path is refused, as is a list that is too long", async () => {
for (const bad of [["https://evil.example"], ["//evil.example"], ["servers"], ["/a b"], ["/<script>"], [42], ["/" + "x".repeat(200)]]) {
assert.equal((await put(bad)).status, 400, JSON.stringify(bad));
}
assert.equal((await put(Array.from({ length: MAX_FAVORITES + 1 }, (_, i) => `/p${i}`))).status, 400);
assert.equal((await fetch(`${base}/favorites`, { method: "PUT", headers: { "content-type": "application/json" }, body: "{}" })).status, 400);
assert.deepEqual((await me()).favorites, ["/secrets"], "a refused change leaves the list as it was");
});
test("without a session there is nothing to read or change", async () => {
who = "";
assert.equal((await fetch(base)).status, 401);
assert.equal((await put(["/servers"])).status, 401);
who = "anna";
});
});