Files
OwnCord/Client/tauri-client/tests/unit/settings-helpers.test.ts
T
J3vbandClaude Opus 5 ea0430c5b0 fix: batch of correctness fixes across server and client (#1375)
* fix(client): 1 defect(s) (OC-0201)

* fix(service): 1 defect(s) (OC-0202)

HandleTyping built the per-user-per-channel rate-limit key before resolving the channel or checking read permission, so forged channel ids could pin unbounded dead entries in the shared process-wide RateLimiter.

* fix(client): 2 defect(s) (OC-0203, OC-0224)

* fix(server): 1 defect(s) (OC-0204)

* fix(ws): 2 defect(s) (OC-0205, OC-0211)

* fix(admin): 2 defect(s) (OC-0209, OC-0212)

* fix(client): 1 defect(s) (OC-0210)

* fix(db): 1 defect(s) (OC-0213)

* fix(ws): 1 defect(s) (OC-0214)

Route handler-driven PresenceEvent through BroadcastToAll instead of BroadcastToAllLow so every source of a user's presence shares one ordered per-client FIFO.

* fix(admin): 1 defect(s) (OC-0215)

PATCH /users/{id} combining banned + role_id committed and broadcast the ban before authorizing the role change, so a refused role change returned an error while leaving the target banned. Authorize the role change up front via the new ModerationService.AuthorizeRoleChange.

* fix(db): 1 defect(s) (OC-0216)

LinkAttachmentsToMessage no longer claims an attachment that is a user's live avatar (users.avatar points at it). Once message_id is set, handleServeFile's avatar branch (gated on ChannelID == nil) is unreachable and the file falls under the message's channel ACL / soft-delete state, permanently disagreeing with users.avatar about who may read it.

* fix(emoji): 1 defect(s) (OC-0217)

* fix(client): 1 defect(s) (OC-0218)

The data-copy phase of an HTTP proxy tunnel was unbounded. Steps 1-2 of
handle_connection (header read, TCP connect, TLS handshake) each run under
a 10s guard, but step 3 called io::copy_bidirectional with no deadline. A
remote that completes the TLS handshake and then neither responds nor
closes parks the spawned connection task, the loopback socket and the
remote TLS session indefinitely: copy_bidirectional only resolves once
BOTH directions finish, so closing the local side alone does not free it.

Wrap the copy in copy_with_deadline, a generic helper bounded by
DATA_PHASE_TIMEOUT (600s). The bound is deliberately far looser than the
10s setup guards because this phase carries the REST body, including
attachment and avatar uploads, so it must reclaim only genuinely stuck
connections rather than merely slow ones. The helper is generic over the
stream types so it can be exercised without a live TLS connection.

Regression test drives two in-memory duplex pairs whose far ends stay
alive, so neither half ever observes EOF and raw copy_bidirectional would
block forever; the test asserts the call resolves on its own deadline with
ErrorKind::TimedOut.

Claude-Session: https://claude.ai/code/session_01ENMDTh8gDLiHCaRFdMYRiL

* fix(ws): 1 defect(s) (OC-0219)

* fix(client): 1 defect(s) (OC-0221)

UpdateNotifier scheduled its deferred update check with a setTimeout whose
handle was never retained, so destroy() could not cancel it. A component torn
down inside the 3s window (page swap / logout) still fired performCheck() and
issued a network update check against the old server URL. Retain the timer
handle and clear it in destroy().

* fix(dm): 1 defect(s) (OC-0222)

* fix(client): 1 defect(s) (OC-0223)

* fix(voice): 1 defect(s) (OC-0225)

The Grant-Microphone retry's .finally hardcoded grantMicBtn.disabled = false, undoing updateFrozen()'s socket-down freeze when the WS socket dropped while the mic permission request was in flight. Delegate the state back to render().

* fix(admin): 1 defect(s) (OC-0226)

handleApplyUpdate broadcasts a 'restarting in 5s' notice before the on-disk
swap. Every failure path in the swap returned silently, leaving clients
counting down to a restart that never happened. Extract the swap into
applyStagedUpdate and send a corrective 'update_aborted' broadcast from a
deferred guard on every path that does not reach the respawn.

* fix(admin): 1 defect(s) (OC-0227)

PATCH /channels/{id} accepted a blank or whitespace-only name, leaving the
channel unidentifiable in clients. updateChannelRequest.validate() now
rejects it the way handleCreateChannel already did.

* fix(identity): 1 defect(s) (OC-0228)

* fix(admin): run deferred cleanup before the update restart exits

The fix batch left three golangci-lint findings and two prettier findings
that CI gates on.

applyStagedUpdate called os.Exit(0) in the same function that defers both
staged.Close() and the corrective "update_aborted" broadcast, so neither
ran (gocritic exitAfterDefer). Return a bool instead and let the caller
exit once those defers have run — on Windows, releasing the staged binary's
file handle is the reason the restart exists at all, so this is a real fix
rather than a lint appeasement. The exported test hook calls the function as
a statement, so the added result does not affect it.

Also modernize a bulk-insert loop to range-over-int, compare backup bytes
with bytes.Equal, and reflow two test files to prettier's output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ENMDTh8gDLiHCaRFdMYRiL

* test(ws): pin the live presence path against the invisible custom-status leak

OC-0207 and OC-0211 are the same defect at two emitters: hub_broadcast.go's
BroadcastPresence (connect/reconnect) and event.go's presenceEvents (live
presence_update). The fix for OC-0211 closed both sites in one change, but
only the hub_broadcast side got a regression test.

This pins the event.go sibling: an invisible user's real custom status must
be blanked on the PresenceOthersEvent frame while the owner's own
PresenceSelfEvent still carries it. Without it, a later change could reopen
the live path while the committed test kept passing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ENMDTh8gDLiHCaRFdMYRiL

* fix(ws): 1 defect(s) (OC-0206)

* test(ws): silence a contextcheck false positive in the reconnect race test

RefreshChannelVisibility takes no context by design — it is reached through
the admin HubBroadcaster interface, which carries none, so it builds its own
internally. contextcheck flags the call only because the test closure around
it holds a ctx for its override write, so there is nothing to propagate.
Suppress at the call site rather than widen a production interface (and its
mocks) to satisfy a lint in a test.

golangci-lint v2.11.3 (the version ci.yml pins) now reports 0 issues.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ENMDTh8gDLiHCaRFdMYRiL

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-15 16:30:05 +02:00

220 lines
7.9 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
loadPref,
savePref,
applyTheme,
STORAGE_PREFIX,
THEMES,
} from "../../src/components/settings/helpers";
import type { ThemeName } from "../../src/components/settings/helpers";
describe("settings/helpers", () => {
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
localStorage.clear();
});
afterEach(() => {
container.remove();
localStorage.clear();
});
describe("STORAGE_PREFIX", () => {
it("has the correct prefix value", () => {
expect(STORAGE_PREFIX).toBe("owncord:settings:");
});
});
describe("loadPref", () => {
it("returns fallback when key does not exist", () => {
const result = loadPref("nonexistent", "default");
expect(result).toBe("default");
});
it("returns stored value when key exists", () => {
localStorage.setItem(STORAGE_PREFIX + "theme", JSON.stringify("midnight"));
const result = loadPref("theme", "dark");
expect(result).toBe("midnight");
});
it("returns fallback on invalid JSON", () => {
localStorage.setItem(STORAGE_PREFIX + "broken", "not-valid-json");
const result = loadPref("broken", "fallback");
expect(result).toBe("fallback");
});
it("handles boolean values", () => {
localStorage.setItem(STORAGE_PREFIX + "notifications", JSON.stringify(true));
expect(loadPref("notifications", false)).toBe(true);
});
it("handles numeric values", () => {
localStorage.setItem(STORAGE_PREFIX + "volume", JSON.stringify(75));
expect(loadPref("volume", 50)).toBe(75);
});
it("handles object values", () => {
const obj = { fontSize: 14, compact: true };
localStorage.setItem(STORAGE_PREFIX + "display", JSON.stringify(obj));
const result = loadPref("display", {});
expect(result).toEqual(obj);
});
});
describe("savePref", () => {
it("stores value with correct prefix", () => {
savePref("theme", "midnight");
const raw = localStorage.getItem(STORAGE_PREFIX + "theme");
expect(raw).toBe(JSON.stringify("midnight"));
});
it("stores boolean values", () => {
savePref("notifications", true);
const raw = localStorage.getItem(STORAGE_PREFIX + "notifications");
expect(raw).toBe("true");
});
it("stores numeric values", () => {
savePref("volume", 80);
const raw = localStorage.getItem(STORAGE_PREFIX + "volume");
expect(raw).toBe("80");
});
it("stores object values", () => {
const obj = { a: 1, b: "two" };
savePref("config", obj);
const raw = localStorage.getItem(STORAGE_PREFIX + "config");
expect(JSON.parse(raw!)).toEqual(obj);
});
it("overwrites existing values", () => {
savePref("theme", "dark");
savePref("theme", "light");
expect(loadPref("theme", "dark")).toBe("light");
});
});
describe("applyTheme", () => {
it("sets CSS custom properties for dark theme", () => {
applyTheme("dark");
const root = document.documentElement;
expect(root.style.getPropertyValue("--bg-primary")).toBe("#313338");
expect(root.style.getPropertyValue("--bg-secondary")).toBe("#2b2d31");
expect(root.style.getPropertyValue("--bg-tertiary")).toBe("#1e1f22");
expect(root.style.getPropertyValue("--text-normal")).toBe("#dbdee1");
});
it("sets CSS custom properties for midnight theme", () => {
applyTheme("midnight");
const root = document.documentElement;
expect(root.style.getPropertyValue("--bg-primary")).toBe("#1a1a2e");
});
it("sets CSS custom properties for light theme", () => {
applyTheme("light");
const root = document.documentElement;
expect(root.style.getPropertyValue("--bg-primary")).toBe("#ffffff");
expect(root.style.getPropertyValue("--text-normal")).toBe("#313338");
});
it("overwrites previous theme variables", () => {
applyTheme("dark");
applyTheme("light");
const root = document.documentElement;
expect(root.style.getPropertyValue("--bg-primary")).toBe("#ffffff");
});
it("switching away from light clears the light-only tokens instead of leaving them stuck on <html>", () => {
// OC-0201: applyTheme only ever *sets* the keys present in the new
// theme and never clears keys the previous theme set. THEMES.light
// defines ~24 custom properties while dark/midnight/neon-glow define
// only 4, so switching light -> dark must leave zero light-only
// tokens behind on document.documentElement.
applyTheme("light");
const root = document.documentElement;
expect(root.style.getPropertyValue("--bg-input")).toBe("#ebedef");
applyTheme("dark");
// The 4 keys dark actually owns must reflect dark's values.
expect(root.style.getPropertyValue("--bg-primary")).toBe("#313338");
expect(root.style.getPropertyValue("--text-normal")).toBe("#dbdee1");
// Every light-only token must be cleared, not left stuck at its
// light-mode value (which would outrank the :root CSS default via
// inline-style specificity).
const lightOnlyKeys = Object.keys(THEMES.light).filter((k) => !(k in THEMES.dark));
expect(lightOnlyKeys.length).toBeGreaterThan(0);
for (const key of lightOnlyKeys) {
expect(
root.style.getPropertyValue(key),
`${key} must be cleared after switching to dark`,
).toBe("");
}
});
it("does not clear unrelated inline custom properties like --accent or --font-size", () => {
const root = document.documentElement;
root.style.setProperty("--accent", "#00c8ff");
root.style.setProperty("--font-size", "18px");
applyTheme("light");
applyTheme("dark");
expect(root.style.getPropertyValue("--accent")).toBe("#00c8ff");
expect(root.style.getPropertyValue("--font-size")).toBe("18px");
});
it("light theme overrides the dark-mode input/border/interactive tokens so composer and form fields aren't dark-on-dark", () => {
// OC-0043: the light theme only overrode 4 of ~45 tokens. --bg-input
// (used by .message-input-box, .msg-textarea, .form-input, .reply-bar-inner)
// was never overridden, so it kept tokens.css's dark default while
// --text-normal flipped to dark text -- unreadable dark-on-dark.
applyTheme("light");
const root = document.documentElement;
const darkDefaults: Record<string, string> = {
"--bg-input": "#383a40",
"--bg-hover": "#35373c",
"--bg-active": "#404249",
"--border": "#3f4147",
"--border-strong": "#4e5058",
"--text-muted": "#949ba4",
"--text-faint": "#80848e",
"--text-micro": "#6d6f78",
"--header-primary": "#f2f3f5",
"--header-secondary": "#b5bac1",
"--interactive-normal": "#b5bac1",
"--interactive-hover": "#dbdee1",
"--interactive-active": "#fff",
"--interactive-muted": "#4e5058",
};
for (const [token, darkValue] of Object.entries(darkDefaults)) {
const applied = root.style.getPropertyValue(token);
expect(applied, `${token} must be set by the light theme`).not.toBe("");
expect(applied, `${token} must not keep its dark-mode value`).not.toBe(darkValue);
}
});
});
describe("THEMES", () => {
it("contains dark, midnight, and light themes", () => {
const themeNames = Object.keys(THEMES);
expect(themeNames).toContain("dark");
expect(themeNames).toContain("midnight");
expect(themeNames).toContain("light");
});
it("each theme has required CSS variables", () => {
for (const [, vars] of Object.entries(THEMES)) {
expect(vars).toHaveProperty("--bg-primary");
expect(vars).toHaveProperty("--bg-secondary");
expect(vars).toHaveProperty("--bg-tertiary");
expect(vars).toHaveProperty("--text-normal");
}
});
});
});