feat: reorganize settings and add synced appearance preferences

This commit is contained in:
NoSetViolin committed 2026-10-12 18:26:53 +09:00
1 parent 28c128d0c9
commit 8d750d19b0
30 files changed
+835 -98

No files matched your search

+23 -1
View File
@@ -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")
+3
View File
@@ -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);
+8
View File
@@ -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<UserRow>;
@@ -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;
},
+25
View File
@@ -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 () => {
+18
View File
@@ -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") {