diff --git a/src/data/database.test.ts b/src/data/database.test.ts index 64da9dc..797a71d 100644 --- a/src/data/database.test.ts +++ b/src/data/database.test.ts @@ -37,13 +37,35 @@ describe("database", () => { const userCols = botDb.db.prepare("PRAGMA table_info(users)").all() as Array<{ name: string }>; const userColNames = userCols.map((c) => c.name).sort(); - expect(userColNames).toEqual(["createdAt", "id", "passwordHash", "role", "updatedAt", "username"]); + expect(userColNames).toEqual(["accentColor", "createdAt", "id", "passwordHash", "role", "updatedAt", "username"]); const sessionCols = botDb.db.prepare("PRAGMA table_info(sessions)").all() as Array<{ name: string }>; const sessionColNames = sessionCols.map((c) => c.name).sort(); expect(sessionColNames).toEqual(["createdAt", "expiresAt", "id", "lastSeenAt", "userId"]); }); + it("migrates existing accounts and preserves their accent across database reopen", async () => { + const dir = mkdtempSync(join(tmpdir(), 'tsmb-accent-')); + const path = join(dir, 'test.db'); + let db = createDatabase(path); + try { + const user = await createUserStore(db.db).createUser('alice', 'test-password', 'member'); + db.db.exec('ALTER TABLE users DROP COLUMN accentColor'); + db.close(); + db = createDatabase(path); + const users = createUserStore(db.db); + expect(users.getAccentColor(user.id)).toBe('#335eea'); + users.setAccentColor(user.id, '#0891b2'); + db.close(); + db = createDatabase(path); + expect(createUserStore(db.db).getAccentColor(user.id)).toBe('#0891b2'); + expect(createUserStore(db.db).findById(user.id)?.username).toBe('alice'); + } finally { + db.close(); + rmSync(dir, { recursive: true, force: true }); + } + }); + it("creates user_audit table on init", () => { const tables = botDb.db .prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name") diff --git a/src/data/database.ts b/src/data/database.ts index 950850e..fc0f6c4 100644 --- a/src/data/database.ts +++ b/src/data/database.ts @@ -210,6 +210,9 @@ function migrateSchema(db: Database.Database): void { if (!userColNames.includes("role")) { db.exec("ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'admin'"); } + if (!userColNames.includes("accentColor")) { + db.exec("ALTER TABLE users ADD COLUMN accentColor TEXT NOT NULL DEFAULT '#335eea'"); + } const historyColumns = db.prepare("PRAGMA table_info(play_history)").all() as Array<{ name: string }>; const historyColNames = historyColumns.map((c) => c.name); diff --git a/src/data/users.ts b/src/data/users.ts index dbb530b..78a32b3 100644 --- a/src/data/users.ts +++ b/src/data/users.ts @@ -22,6 +22,8 @@ export interface UserRow { } export interface UserStore { + getAccentColor(userId: string): string; + setAccentColor(userId: string, color: string): boolean; countUsers(): number; countAdmins(): number; createUser(username: string, password: string, role: UserRole): Promise; @@ -68,6 +70,12 @@ export function createUserStore(db: Database.Database): UserStore { const deleteUserStmt = db.prepare("DELETE FROM users WHERE id = ?"); return { + getAccentColor(userId) { + return (db.prepare("SELECT accentColor FROM users WHERE id = ?").get(userId) as { accentColor: string } | undefined)?.accentColor ?? "#335eea"; + }, + setAccentColor(userId, color) { + return db.prepare("UPDATE users SET accentColor = ?, updatedAt = ? WHERE id = ? AND role != 'guest'").run(color, Date.now(), userId).changes > 0; + }, countUsers() { return (countStmt.get() as { n: number }).n; }, diff --git a/src/web/api/session.test.ts b/src/web/api/session.test.ts index 5e16ab1..b60dff3 100644 --- a/src/web/api/session.test.ts +++ b/src/web/api/session.test.ts @@ -127,6 +127,29 @@ describe("session router", () => { expect(anon.status).toBe(401); }); + it("stores accent preferences per account and returns them to other sessions", async () => { + const alice = await users.createUser("alice", "pw-alice", "member"); + const bob = await users.createUser("bob", "pw-bob", "member"); + const cookieA = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`; + const cookieB = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`; + const updated = await request(app).put('/api/session/preferences').set('Cookie', cookieA) + .send({ accentColor: '#8B5CF6', userId: bob.id }); + expect(updated.status).toBe(200); + expect(updated.body.accentColor).toBe('#8b5cf6'); + expect((await request(app).get('/api/session/me').set('Cookie', cookieB)).body.accentColor).toBe('#8b5cf6'); + expect(users.getAccentColor(bob.id)).toBe('#335eea'); + }); + + it("rejects anonymous and invalid preference updates without altering the account", async () => { + const alice = await users.createUser("alice", "pw-alice", "member"); + const cookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`; + expect((await request(app).put('/api/session/preferences').send({ accentColor: '#8b5cf6' })).status).toBe(401); + for (const accentColor of ['red', '#fff', '#zzzzzz', null, 123]) { + expect((await request(app).put('/api/session/preferences').set('Cookie', cookie).send({ accentColor })).status).toBe(400); + } + expect(users.getAccentColor(alice.id)).toBe('#335eea'); + }); + it("POST /logout deletes the session and clears the cookie", async () => { await users.createUser("alice", "pw-alice", "admin"); const loginRes = await request(app) @@ -300,6 +323,8 @@ describe("session router — guest mode", () => { expect(me.body.guest.addToQueue).toBe(true); expect(me.body.guest.playNext).toBe(true); expect(me.body.capabilities).toEqual([]); + expect(me.body.accentColor).toBeNull(); + expect((await request(app).put('/api/session/preferences').set('Cookie', cookie).send({ accentColor: '#8b5cf6' })).status).toBe(403); }); it("GET /needs-setup exposes guestAllowed", async () => { diff --git a/src/web/api/session.ts b/src/web/api/session.ts index 5c56a02..fe87b89 100644 --- a/src/web/api/session.ts +++ b/src/web/api/session.ts @@ -182,9 +182,27 @@ export function createSessionRouter( capabilities: [...ctx.capabilities], bots: ctx.bots === "all" ? "all" : [...ctx.bots], guest: ctx.guest ?? null, + accentColor: user.role === "guest" ? null : users.getAccentColor(user.id), }); }); + router.put("/preferences", requireAuthInline, (req, res) => { + if (req.user!.role === "guest") { + res.status(403).json({ error: "guests store appearance preferences locally" }); + return; + } + const color = req.body?.accentColor; + if (typeof color !== "string" || !/^#[0-9a-fA-F]{6}$/.test(color)) { + res.status(400).json({ error: "invalid accent color" }); + return; + } + if (!users.setAccentColor(req.user!.id, color.toLowerCase())) { + res.status(404).json({ error: "user not found" }); + return; + } + res.json({ accentColor: color.toLowerCase() }); + }); + router.post("/change-password", requireAuthInline, async (req, res) => { const { oldPassword, newPassword } = req.body ?? {}; if (typeof oldPassword !== "string") { diff --git a/web/index.html b/web/index.html index 425308f..441fb73 100644 --- a/web/index.html +++ b/web/index.html @@ -35,8 +35,8 @@ full square. Android reads the manifest instead. --> - + + diff --git a/web/src/App.vue b/web/src/App.vue index 55e5675..cd5fbb8 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -1,5 +1,5 @@