Fix critical and high audit findings

Fixed findings from the audit reports (SECURITY, QUALITY, PERFORMANCE):
- P-001 · Dashboard re-downloads the entire dataset every 5 seconds

Re-synced the vendored shared/ snapshot from shared commit 199a5ef.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Haiku 5.5 committed 2026-10-19 07:48:07 +00:00
1 parent 7dd0d34383
commit a84a36349b
31 files changed
+653 -6055

No files matched your search

@@ -715,9 +715,13 @@ public final class AuthClient {
if (candidate.startsWith(prefix)) {
String value = candidate.substring(prefix.length());
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
// URLDecoder would turn a literal "+" into a space; escape it first so it survives, as in Node.
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
return value;
} catch (IllegalArgumentException ex) {
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
return "";
}
}
}
@@ -218,6 +218,34 @@ class AuthClientTest {
assertEquals("right", token);
}
@Test
void extractTokenKeepsALiteralPlusSignInTheCookieValue() {
AuthClient client = new AuthClient("https://auth.example.com");
String token = client.extractToken(name -> null, "auth_session=ab+cd%2Bef");
assertEquals("ab+cd+ef", token);
}
@Test
void extractTokenTreatsAMalformedCookieEscapeAsNoToken() {
AuthClient client = new AuthClient("https://auth.example.com");
String token = client.extractToken(name -> null, "auth_session=bad%zz; other=1");
assertEquals("", token);
}
@Test
void middlewareFailsClosedOnAMalformedCookieInsteadOfThrowing() throws Exception {
AuthClient client = new AuthClient("https://auth.example.com");
String result = client.middleware(name -> null, "auth_session=100%",
user -> "authenticated", () -> "unauthorized");
assertEquals("unauthorized", result);
}
@Test
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
server = fakeAuthGuard(401, "{\"valid\":false}");
@@ -1,15 +0,0 @@
{
"extends": ["stylelint-config-standard"],
"ignoreFiles": ["public/css/index.css", "**/*.min.css"],
"rules": {
"at-rule-no-unknown": [true, { "ignoreAtRules": ["layer", "apply", "config"] }],
"selector-class-pattern": null,
"keyframes-name-pattern": null,
"custom-property-pattern": null,
"no-descending-specificity": null,
"import-notation": null,
"comment-empty-line-before": null,
"declaration-property-value-no-unknown": null,
"value-keyword-case": ["lower", { "camelCaseSvgKeywords": true }]
}
}
-16
View File
@@ -1,16 +0,0 @@
# @gabriel20xx/legacy-assets
This package now contains exactly one file: `public/css/index.css`, a static (pre-Tailwind-v4)
theme stylesheet. Its only remaining consumer is `Original/MediaDesktop`'s Electron renderer,
which still uses the old `--color-*` utility-class theme rather than the current `--sc-*`
design-token system in `packages/design-tokens`. It's a `file:` dependency there
(`scripts/copy-assets.mjs` copies `index.css` into `MediaDesktop/public/` at build time) - do not
delete this package without first migrating MediaDesktop off the old stylesheet.
Everything else that used to live here (the pre-SvelteKit `public/js/*` auth/layout/media
utilities, an orphaned `MediaDesktop/assets/icon.png` copy, and the broken monorepo-era
`build:theme` script) was removed: nothing else in the workspace referenced any of it.
Originally `MediaCollection/MediaShared`, moved here to centralize shared components. Both the
`MediaCollection` and `MediaShared` umbrella names are retired - everything here is just part of
`shared` now, workspace-wide.
@@ -1,13 +0,0 @@
{
"name": "@gabriel20xx/legacy-assets",
"version": "3.0.0",
"private": true,
"description": "Legacy pre-SvelteKit theme CSS, kept only for MediaDesktop's Electron renderer (file: dependency)",
"scripts": {
"lint:css": "stylelint \"public/**/*.css\""
},
"exports": {
"./index.css": "./public/css/index.css"
},
"files": ["public/**"]
}
File diff suppressed because it is too large. Load diff
@@ -211,9 +211,8 @@ export class AuthClient {
*/
middleware() {
return async (req, res, next) => {
const token = this.tokenFromRequest(req);
try {
req.authUser = await this.validate(token);
req.authUser = await this.validate(this.tokenFromRequest(req));
next();
} catch {
// Fail closed on both an invalid session and a transport/decoding
@@ -236,7 +235,14 @@ export class AuthClient {
.split(';')
.map(part => part.trim())
.find(part => part.startsWith(`${this.cookieName}=`));
if (match) return decodeURIComponent(match.slice(this.cookieName.length + 1));
if (match) {
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
try {
return decodeURIComponent(match.slice(this.cookieName.length + 1));
} catch {
return '';
}
}
}
return '';
}
@@ -125,6 +125,29 @@ test('tokenFromRequest falls back to the auth_session cookie', () => {
assert.equal(client.tokenFromRequest(req), 'cookie-token');
});
test('tokenFromRequest treats a malformed cookie escape as no token', () => {
const client = new AuthClient('https://auth.example.com');
const req = { headers: { cookie: 'auth_session=bad%zz; other=1' } };
assert.equal(client.tokenFromRequest(req), '');
});
test('middleware answers 401 instead of rejecting on a malformed cookie', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
});
let statusCode = null;
const res = {
status(code) {
statusCode = code;
return { json: () => {} };
},
};
await client.middleware()({ headers: { cookie: 'auth_session=100%' } }, res, () => {
throw new Error('next should not be called');
});
assert.equal(statusCode, 401);
});
test('middleware attaches authUser on success and 401s on failure', async () => {
const okClient = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
@@ -94,6 +94,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
# rather than a generic "internal error" indistinguishable from any other bug.
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
ERR_ADMIN_REQUIRED = "Administrator access required."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
# authentication is disabled, either because AUTHGUARD_URL is disabled or
@@ -338,6 +339,23 @@ def build_auth_router(
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return token
async def require_admin(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind an administrator session
(the Python counterpart of Go's RequireAdmin). Unlike require_session it
never falls back to _LOCAL_PROFILE, so a route that changes the
login-required flag cannot be called anonymously, even while login is
already disabled."""
if not _enabled(client):
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
if not can_manage_users(profile.role):
raise HTTPException(status_code=403, detail=ERR_ADMIN_REQUIRED)
return profile
# --- status / me -------------------------------------------------------
@router.get("/me")
@@ -561,6 +579,7 @@ def build_auth_router(
async def update_access_settings(
req: UpdateAccessRequest,
store: ProxyStore = Depends(get_store), # noqa: B008
_admin: PublicUser = Depends(require_admin), # noqa: B008
) -> dict[str, bool]:
nonlocal login_required_override
await store.set_login_required(req.loginRequired)
@@ -4,7 +4,13 @@ from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from shared_backend import authproxy as ap
from shared_backend.authclient import APIError, AuthClient, PublicUser, SessionResult
from shared_backend.authclient import (
DEFAULT_COOKIE_NAME,
APIError,
AuthClient,
PublicUser,
SessionResult,
)
class _FakeStore(ap.ProxyStore):
@@ -113,14 +119,32 @@ class AuthDisabledModeTests(unittest.TestCase):
class AccessSettingsTests(unittest.TestCase):
def test_get_and_put_round_trip_through_the_store(self) -> None:
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
client = TestClient(_build_app(store, _RoleClient()))
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 401)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 403)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
client.cookies.set(DEFAULT_COOKIE_NAME, "admin-token")
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.json(), {"loginRequired": False})
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
def test_anonymous_put_is_refused_when_authguard_is_not_configured(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 401)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(
@@ -180,6 +204,16 @@ class _FakeClient(AuthClient):
return ["auth_session=; Path=/; Max-Age=0"]
class _RoleClient(_FakeClient):
"""Resolves two fixed session tokens to an administrator and an ordinary user."""
async def me(self, token: str) -> PublicUser:
roles = {"admin-token": "superadmin", "user-token": "user"}
if token not in roles:
raise APIError(401, "unauthenticated")
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
class EnabledModeSetupAndLoginTests(unittest.TestCase):
"""Exercises the real (client is not None) path, including the
setup-claim flag's interaction with the store."""
@@ -1,3 +1,6 @@
<!--
Internal to MediaPlayer. Not exported from the package barrel; do not re-export.
-->
<script lang="ts">
import { Maximize2, Minimize2, Pause, Play, Settings, Volume2, VolumeX } from '@lucide/svelte'
import { onMount } from 'svelte'
@@ -1,286 +0,0 @@
<script lang="ts">
import type {
KnownRole,
ManagedUser,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateInput,
UserUpdateRequest
} from '../types';
import Button from './Button.svelte';
import Pagination from './Pagination.svelte';
let {
currentRole = 'user',
currentUserId,
onCreate,
onDelete,
onList,
onUpdate,
roles
}: {
currentRole?: UserRole;
currentUserId?: UserId;
onCreate?: UserCreateRequest;
onDelete?: UserDeleteRequest;
onList?: UserListRequest;
onUpdate?: UserUpdateRequest;
/**
* The custom roles an account can be placed in (AuthGuard's role-based
* project access: a role decides which projects its members may log into).
* Only AuthGuard's own admin UI passes this - every other project's
* UserManagement usage omits it, and the whole role section of this
* component simply doesn't render.
*/
roles?: KnownRole[];
} = $props();
let users = $state<ManagedUser[]>([]);
let loading = $state(false);
let saving = $state(false);
let error = $state('');
let notice = $state('');
let loaded = $state(false);
let newUser = $state<UserCreateInput>({ username: '', email: '', password: '', role: 'user' });
let editingId = $state<UserId | null>(null);
let editUser = $state<UserUpdateInput>({});
let page = $state(1);
let pageSize = $state(24);
const canManage = $derived(currentRole === 'admin' || currentRole === 'superadmin');
const canAssignAdmin = $derived(currentRole === 'superadmin');
const pageCount = $derived(Math.max(1, Math.ceil(users.length / pageSize)));
const currentPage = $derived(Math.min(page, pageCount));
const pagedUsers = $derived(
users.slice((currentPage - 1) * pageSize, (currentPage - 1) * pageSize + pageSize)
);
function roleForForm(role: UserRole | undefined): UserRole {
return canAssignAdmin && role ? role : 'user';
}
function formatLastLogin(value: string | null | undefined): string {
if (!value) return 'Never';
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? 'Never' : parsed.toLocaleString();
}
async function loadUsers(): Promise<void> {
if (!onList || !canManage) return;
loading = true;
error = '';
try {
users = await onList();
loaded = true;
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to load users.';
} finally {
loading = false;
}
}
$effect(() => {
if (canManage && onList && !loaded) void loadUsers();
});
async function createUser(event: SubmitEvent): Promise<void> {
event.preventDefault();
if (!onCreate) return;
if (!newUser.username.trim() && !newUser.email.trim()) {
error = 'A username or email is required.';
return;
}
saving = true;
error = '';
notice = '';
try {
await onCreate({ ...newUser, role: roleForForm(newUser.role) });
newUser = { username: '', email: '', password: '', role: 'user' };
notice = 'User created.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to create user.';
} finally {
saving = false;
}
}
function startEditing(user: ManagedUser): void {
editingId = user.id;
editUser = { username: user.username, email: user.email, role: roleForForm(user.role) };
if (roles && roles.length > 0) editUser.roleIds = [...(user.roleIds ?? [])];
error = '';
notice = '';
}
function toggleEditRole(id: number, checked: boolean): void {
const current = editUser.roleIds ?? [];
editUser.roleIds = checked ? [...current, id] : current.filter((roleId) => roleId !== id);
}
function toggleNewRole(id: number, checked: boolean): void {
const current = newUser.roleIds ?? [];
newUser.roleIds = checked ? [...current, id] : current.filter((roleId) => roleId !== id);
}
// Names the roles an account is in, in the order the roles are listed. An account in none of
// them keeps every project.
function roleSummary(user: ManagedUser): string {
const names = (roles ?? []).filter((role) => (user.roleIds ?? []).includes(role.id)).map((role) => role.name);
return names.length > 0 ? names.join(', ') : 'All projects';
}
function stopEditing(): void {
editingId = null;
editUser = {};
}
async function updateUser(event: SubmitEvent): Promise<void> {
event.preventDefault();
if (!onUpdate || editingId === null) return;
saving = true;
error = '';
notice = '';
try {
const input = { ...editUser, role: roleForForm(editUser.role) };
if (!input.password) delete input.password;
await onUpdate(editingId, input);
stopEditing();
notice = 'User updated.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to update user.';
} finally {
saving = false;
}
}
async function deleteUser(user: ManagedUser): Promise<void> {
if (!onDelete || String(user.id) === String(currentUserId)) return;
if (!window.confirm(`Delete user ${user.username}?`)) return;
saving = true;
error = '';
notice = '';
try {
await onDelete(user.id);
notice = 'User deleted.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to delete user.';
} finally {
saving = false;
}
}
</script>
{#if canManage && onList && onCreate && onUpdate && onDelete}
<section class="sc-user-management" aria-labelledby="sc-user-management-title">
<div class="sc-user-management-header">
<div>
<h3 id="sc-user-management-title">User management</h3>
<p class="sc-muted">Add, edit, or remove accounts for this project.</p>
</div>
<Button disabled={loading || saving} size="sm" type="button" variant="secondary" onclick={() => void loadUsers()}>
Refresh
</Button>
</div>
<form class="sc-user-form" onsubmit={createUser}>
<strong>Add user</strong>
<div class="sc-user-grid">
<input aria-label="New username" class="sc-input" placeholder="Username (optional if email is set)" type="text" bind:value={newUser.username} />
<input aria-label="New email" class="sc-input" placeholder="Email (optional if username is set)" type="email" bind:value={newUser.email} />
<input aria-label="New password" class="sc-input" minlength="8" placeholder="Password (optional)" type="password" bind:value={newUser.password} />
<select aria-label="New role" class="sc-input" disabled={!canAssignAdmin} bind:value={newUser.role}>
<option value="user">User</option>
{#if canAssignAdmin}<option value="admin">Admin</option>{/if}
</select>
</div>
{#if roles && roles.length > 0}
<fieldset class="sc-user-roles">
<legend>Roles (none checked = all projects)</legend>
{#each roles as role (role.id)}
<label class="sc-user-role-option">
<input
type="checkbox"
checked={(newUser.roleIds ?? []).includes(role.id)}
onchange={(event) => toggleNewRole(role.id, event.currentTarget.checked)}
/>
{role.name}
</label>
{/each}
</fieldset>
{/if}
<div class="sc-form-actions"><Button disabled={saving} type="submit">Add user</Button></div>
</form>
{#if error}<p aria-live="polite" class="sc-error">{error}</p>{/if}
{#if notice}<p aria-live="polite" class="sc-success">{notice}</p>{/if}
{#if loading && users.length === 0}
<p class="sc-muted">Loading users...</p>
{:else if users.length === 0}
<p class="sc-muted">No users found.</p>
{:else}
<div class="sc-user-list">
{#each pagedUsers as user (user.id)}
{#if String(editingId) === String(user.id)}
<form class="sc-user-row sc-user-edit-row" onsubmit={updateUser}>
<input aria-label="Username" class="sc-input" required type="text" bind:value={editUser.username} />
<input aria-label="Email" class="sc-input" required type="email" bind:value={editUser.email} />
<input aria-label="New password" class="sc-input" minlength="8" placeholder="Keep password" type="password" bind:value={editUser.password} />
<select aria-label="Role" class="sc-input" disabled={!canAssignAdmin || user.role === 'superadmin'} bind:value={editUser.role}>
<option value="user">User</option>
{#if canAssignAdmin}<option value="admin">Admin</option>{/if}
{#if user.role === 'superadmin'}<option value="superadmin">Superadmin</option>{/if}
</select>
{#if roles && roles.length > 0}
<fieldset class="sc-user-roles">
<legend>Roles (none checked = all projects)</legend>
{#each roles as role (role.id)}
<label class="sc-user-role-option">
<input
type="checkbox"
checked={(editUser.roleIds ?? []).includes(role.id)}
onchange={(event) => toggleEditRole(role.id, event.currentTarget.checked)}
/>
{role.name}
</label>
{/each}
</fieldset>
{/if}
<div class="sc-user-actions"><Button disabled={saving} size="sm" type="submit">Save</Button><Button disabled={saving} size="sm" type="button" variant="secondary" onclick={stopEditing}>Cancel</Button></div>
</form>
{:else}
<div class="sc-user-row">
<div><strong>{user.username}</strong><span>{user.email}</span></div>
<span class="sc-user-role">{user.role}</span>
<span class="sc-muted sc-user-last-login" title="Last login">{formatLastLogin(user.lastLoginAt)}</span>
{#if roles && roles.length > 0}
<span class="sc-muted sc-user-roles-summary" title="Roles">{roleSummary(user)}</span>
{/if}
<div class="sc-user-actions">
<Button disabled={saving} size="sm" type="button" variant="secondary" onclick={() => startEditing(user)}>Edit</Button>
<Button disabled={saving || String(user.id) === String(currentUserId) || user.role === 'superadmin'} size="sm" type="button" variant="danger" onclick={() => void deleteUser(user)}>Remove</Button>
</div>
</div>
{/if}
{/each}
</div>
<Pagination
page={currentPage}
{pageSize}
pageLength={pagedUsers.length}
totalLength={users.length}
onPaging={(change) => {
page = change.page;
pageSize = change.pageSize;
}}
/>
{/if}
</section>
{/if}
-6
View File
@@ -9,7 +9,6 @@ export { default as EmptyState } from './components/EmptyState.svelte';
export { default as Header } from './components/Header.svelte';
export { default as Metric } from './components/Metric.svelte';
export { default as MediaPlayer } from './components/MediaPlayer.svelte';
export { default as MediaPlayerControls } from './components/MediaPlayerControls.svelte';
export { default as NotificationStack } from './components/NotificationStack.svelte';
export { default as Pagination } from './components/Pagination.svelte';
export { default as ProfileDialog } from './components/ProfileDialog.svelte';
@@ -19,7 +18,6 @@ export { default as SettingsDialog } from './components/SettingsDialog.svelte';
export { default as StatusDialog } from './components/StatusDialog.svelte';
export { default as StatusWidget } from './components/StatusWidget.svelte';
export { default as TotpSettings } from './components/TotpSettings.svelte';
export { default as UserManagement } from './components/UserManagement.svelte';
export { notifications, notify } from './notifications.svelte';
export {
PRIMARY_COLOR_PALETTE,
@@ -49,13 +47,9 @@ export type {
StatusProbe,
StatusSnapshot,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateInput,
UserUpdateRequest,
TotpSetupRequest,
TotpSetupResponse,
TotpStatusRequest,
@@ -39,9 +39,10 @@ const paletteByName = Object.fromEntries(PRIMARY_COLOR_PALETTE.map((color) => [c
string,
PaletteColor
>
const primaryVars = ['--color-primary', '--color-accent', '--color-ring']
const foregroundVars = ['--color-primary-fg', '--color-accent-fg']
const primaryVars = ['--color-primary', '--color-accent', '--color-ring', '--sc-primary', '--sc-accent', '--sc-ring']
const foregroundVars = ['--color-primary-fg', '--color-accent-fg', '--sc-primary-fg', '--sc-accent-fg']
const activeUserAttribute = 'data-primary-color-user'
const styleElementId = 'sc-primary-color'
const activeProjects = new Set<string>()
function normalizeUserKey(userKey: string): string {
@@ -67,19 +68,45 @@ function readStoredColor(projectKey: string): string {
}
}
// Moves a #rrggbb color a fraction of the way toward a channel value (0 = black, 255 = white).
function mixHex(hex: string, towards: number, weight: number): string {
const channels = [1, 3, 5].map((start) => parseInt(hex.slice(start, start + 2), 16))
return `#${channels.map((c) => Math.round(c + (towards - c) * weight).toString(16).padStart(2, '0')).join('')}`
}
// The color is written to a stylesheet rather than inline on <html>. Shared and app CSS re-declare these
// tokens on every [data-theme] element (the AppShell root, for one), and that declaration hides the value
// <html> would pass down, so the choice never reached the app's UI. Targeting [data-theme] elements with
// !important makes it win everywhere, and the dark/light split is left to the selectors.
function primaryDeclarations(color: PaletteColor, dark: boolean): string {
const primary = dark ? color.dark : color.light
// Hover is lighter on dark and darker on light, as in the shared theme. It is a hex value, not color-mix(),
// because consumers such as the terminal read these tokens as plain colors.
const hover = dark ? mixHex(primary, 255, 0.15) : mixHex(primary, 0, 0.15)
const foreground = dark ? color.darkFg : '#ffffff'
return [
...primaryVars.map((name) => `${name}: ${primary} !important;`),
`--sc-primary-hover: ${hover} !important;`,
...foregroundVars.map((name) => `${name}: ${foreground} !important;`),
].join(' ')
}
export function applyPrimaryColor(_projectKey: string, colorName: string): void {
if (typeof document === 'undefined') return
const color = paletteByName[colorName]
const root = document.documentElement.style
let style = document.getElementById(styleElementId) as HTMLStyleElement | null
if (!color) {
for (const name of [...primaryVars, ...foregroundVars]) root.removeProperty(name)
style?.remove()
return
}
const dark = document.documentElement.getAttribute('data-theme') === 'dark'
const primary = dark ? color.dark : color.light
const foreground = dark ? color.darkFg : '#ffffff'
for (const name of primaryVars) root.setProperty(name, primary)
for (const name of foregroundVars) root.setProperty(name, foreground)
if (!style) {
style = document.createElement('style')
style.id = styleElementId
document.head.append(style)
}
style.textContent = `:root, [data-theme] { ${primaryDeclarations(color, false)} }
[data-theme='dark'] { ${primaryDeclarations(color, true)} }
`
}
export function setPrimaryColor(projectKey: string, colorName: string): void {
@@ -105,11 +132,8 @@ export function initPrimaryColor(projectKey: string, userKey = ''): () => void {
if (typeof document === 'undefined') return () => undefined
if (userKey) setPrimaryColorUser(userKey)
activeProjects.add(projectKey.trim().toLowerCase() || 'application')
const stored = readStoredColor(projectKey)
applyPrimaryColor(projectKey, stored)
const observer = new MutationObserver(() => applyPrimaryColor(projectKey, readStoredColor(projectKey)))
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
return () => observer.disconnect()
applyPrimaryColor(projectKey, readStoredColor(projectKey))
return () => undefined
}
export function storedPrimaryColor(projectKey: string): string {
-142
View File
@@ -746,148 +746,6 @@ html[data-wide-layout='true'] .sc-header {
color: var(--sc-success);
}
.sc-user-management {
display: grid;
gap: 1rem;
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--sc-border);
}
.sc-user-management-header,
.sc-user-row,
.sc-user-edit-row {
display: flex;
align-items: center;
gap: 0.75rem;
}
.sc-user-management-header {
justify-content: space-between;
}
.sc-user-management-header h3 {
margin: 0;
}
.sc-user-management-header p {
margin: 0.25rem 0 0;
}
.sc-user-form,
.sc-user-list {
display: grid;
gap: 0.75rem;
}
.sc-user-form {
padding: 0.9rem;
border: 1px solid var(--sc-border);
border-radius: 0.6rem;
background: var(--sc-surface-raised);
}
.sc-user-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.6rem;
}
.sc-user-row {
min-width: 0;
justify-content: space-between;
padding: 0.7rem 0;
border-bottom: 1px solid var(--sc-border);
}
.sc-user-row > div:first-child {
display: grid;
min-width: 0;
}
.sc-user-row > div:first-child span {
overflow: hidden;
color: var(--sc-muted-fg);
text-overflow: ellipsis;
white-space: nowrap;
}
.sc-user-role {
color: var(--sc-muted-fg);
font-size: 0.8rem;
text-transform: capitalize;
}
.sc-user-last-login {
flex-shrink: 0;
font-size: 0.8rem;
white-space: nowrap;
}
.sc-user-actions {
display: flex;
flex-shrink: 0;
gap: 0.4rem;
}
.sc-user-roles-summary {
max-width: 12rem;
overflow: hidden;
font-size: 0.8rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.sc-user-roles {
display: flex;
flex: 1 1 100%;
flex-wrap: wrap;
gap: 0.5rem 1rem;
margin: 0;
padding: 0.5rem 0.7rem;
border: 1px solid var(--sc-border);
border-radius: 0.5rem;
}
.sc-user-roles legend {
flex-basis: 100%;
margin-bottom: 0.3rem;
color: var(--sc-muted-fg);
font-size: 0.8rem;
}
.sc-user-role-option {
display: flex;
align-items: center;
gap: 0.35rem;
font-size: 0.85rem;
}
.sc-user-edit-row {
align-items: stretch;
flex-wrap: wrap;
}
.sc-user-edit-row .sc-input {
flex: 1 1 10rem;
min-width: 8rem;
}
@media (max-width: 620px) {
.sc-user-grid {
grid-template-columns: 1fr;
}
.sc-user-row {
align-items: flex-start;
flex-wrap: wrap;
}
.sc-user-actions {
width: 100%;
}
}
.sc-pagination {
display: flex;
flex-wrap: wrap;
+2 -15
View File
@@ -73,7 +73,7 @@ export interface KnownProject {
label: string;
}
/** One custom role an administrator may assign to a user - see UserManagement's `roles` prop. */
/** One custom role an administrator may assign to a user. */
export interface KnownRole {
id: number;
name: string;
@@ -107,24 +107,11 @@ export interface UserUpdateInput {
/**
* Replaces the account's full set of custom roles when present (an empty
* array removes it from every role); omitted (undefined) leaves them
* untouched. Only ever set when UserManagement was given a `roles` prop.
* untouched.
*/
roleIds?: number[];
}
export type UserListRequest = () => ManagedUser[] | Promise<ManagedUser[]>;
export type UserCreateRequest = (
input: UserCreateInput,
) => void | Promise<void | ManagedUser>;
export type UserUpdateRequest = (
id: UserId,
input: UserUpdateInput,
) => void | Promise<void | ManagedUser>;
export type UserDeleteRequest = (id: UserId) => void | Promise<void>;
export interface AboutLink {
label: string;
href: string;