Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0b8e4e090 | ||
|
|
af11f5119c | ||
|
|
8cab61a9c5 |
@@ -1,5 +1,4 @@
|
||||
VITE_API_BASE_URL=http://localhost:8080
|
||||
VITE_OAUTH_CLIENT_ID=stalwart-webui
|
||||
#VITE_ACCESS_TOKEN=OPEN_SESAME
|
||||
VITE_OAUTH_SCOPES=
|
||||
|
||||
|
||||
+9
-14
@@ -12,19 +12,14 @@ dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
.ignore
|
||||
scripts/
|
||||
*.md
|
||||
!README.md
|
||||
!CHANGELOG.md
|
||||
/SPEC-*
|
||||
|
||||
.*
|
||||
!.gitignore
|
||||
!.prettierrc
|
||||
!.env.development
|
||||
!.github/
|
||||
!.vscode/
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
|
||||
@@ -2,6 +2,38 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [1.0.10] - 2026-09-04
|
||||
|
||||
### Added
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
- Re-added map entries and object list items are seeded with their schema defaults, including a value for every non-nullable boolean.
|
||||
|
||||
## [1.0.9] - 2026-08-24
|
||||
|
||||
### Added
|
||||
- Server configurable OAuth client ID.
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [1.0.8] - 2026-07-31
|
||||
|
||||
### Added
|
||||
- Remember the last visited page when switching sections (credits @LinkPhoenix).
|
||||
|
||||
### Changed
|
||||
- Enum list filters with many options render as a searchable combobox (credits @LinkPhoenix).
|
||||
- Object cells display the variant label as a badge instead of the raw type name (credits @LinkPhoenix).
|
||||
- Empty date pickers open on the current date and time (credits @LinkPhoenix).
|
||||
|
||||
### Fixed
|
||||
- Custom logos no longer flash when navigating between pages.
|
||||
- Landing no longer flashes "Select a view" before redirecting to the default page.
|
||||
|
||||
## [1.0.7] - 2026-07-30
|
||||
|
||||
### Added
|
||||
|
||||
@@ -71,7 +71,6 @@ Configuration is done through Vite environment variables. Copy or edit `.env.dev
|
||||
|
||||
```
|
||||
VITE_API_BASE_URL=http://localhost:443
|
||||
VITE_OAUTH_CLIENT_ID=stalwart-webui
|
||||
VITE_ACCESS_TOKEN=
|
||||
VITE_OAUTH_SCOPES=
|
||||
```
|
||||
@@ -79,10 +78,20 @@ VITE_OAUTH_SCOPES=
|
||||
| Variable | Description |
|
||||
|---|---|
|
||||
| `VITE_API_BASE_URL` | URL of the Stalwart server. Used for all API requests during development. In production builds (when empty or unset) requests are relative to the current origin. |
|
||||
| `VITE_OAUTH_CLIENT_ID` | OAuth 2.0 client ID. Defaults to `stalwart-webui`. |
|
||||
| `VITE_ACCESS_TOKEN` | When set, skips the OAuth flow entirely and uses this token for all requests. Useful for local development and testing. |
|
||||
| `VITE_OAUTH_SCOPES` | Optional OAuth scopes. Omitted from the authorization request when empty. |
|
||||
|
||||
### OAuth client ID
|
||||
|
||||
The OAuth 2.0 client ID is not a build-time setting. It is read at runtime from a meta tag in `index.html`:
|
||||
|
||||
```html
|
||||
<meta name="oauth-client-id" content="" />
|
||||
```
|
||||
|
||||
The server rewrites the `content` attribute when it serves the page, so a single build works for any deployment. When no
|
||||
client ID is configured the attribute is left empty and the panel falls back to `stalwart-webui`.
|
||||
|
||||
### Bypassing OAuth for development
|
||||
|
||||
Set `VITE_ACCESS_TOKEN` to a valid bearer token to skip the login page and go straight to the admin panel. You can obtain a token from the Stalwart server's token endpoint or use an API key:
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<base href="/" />
|
||||
<meta name="oauth-client-id" content="" />
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Portal</title>
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"private": true,
|
||||
"version": "1.0.7",
|
||||
"version": "1.0.10",
|
||||
"description": "Stalwart WebUI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -68,4 +68,4 @@
|
||||
"vite": "^8.2.0",
|
||||
"vitest": "^4.1.10"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { getApiBaseUrl } from '@/services/api';
|
||||
import { getLogoState, loadLogoOnce, subscribeToLogo } from '@/lib/logoCache';
|
||||
|
||||
export function DefaultLogo() {
|
||||
const { t } = useTranslation();
|
||||
@@ -31,54 +31,18 @@ export function DefaultLogo() {
|
||||
|
||||
export default function Logo() {
|
||||
const { t } = useTranslation();
|
||||
const [logoUrl, setLogoUrl] = useState<string | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const logo = useSyncExternalStore(subscribeToLogo, getLogoState, getLogoState);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
async function fetchLogo() {
|
||||
try {
|
||||
const response = await fetch(`${getApiBaseUrl()}/logo`, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
|
||||
if (response.ok && contentType.startsWith('image/')) {
|
||||
const blob = await response.blob();
|
||||
if (!controller.signal.aborted) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
setLogoUrl(url);
|
||||
}
|
||||
} else {
|
||||
if (!controller.signal.aborted) setFailed(true);
|
||||
}
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setFailed(true);
|
||||
}
|
||||
}
|
||||
|
||||
fetchLogo();
|
||||
|
||||
return () => {
|
||||
controller.abort();
|
||||
};
|
||||
loadLogoOnce();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (logoUrl) {
|
||||
URL.revokeObjectURL(logoUrl);
|
||||
}
|
||||
};
|
||||
}, [logoUrl]);
|
||||
|
||||
if (logoUrl && !failed) {
|
||||
return <img src={logoUrl} alt={t('logo.alt', 'Logo')} className="h-7 w-auto max-w-[220px] object-contain" />;
|
||||
if (logo.status === 'custom') {
|
||||
return <img src={logo.url} alt={t('logo.alt', 'Logo')} className="h-7 w-auto max-w-[220px] object-contain" />;
|
||||
}
|
||||
|
||||
if (!failed) {
|
||||
return <div className="h-7" aria-hidden="true" />;
|
||||
if (logo.status === 'loading') {
|
||||
return <span className="block h-7 w-[140px]" aria-hidden="true" />;
|
||||
}
|
||||
|
||||
return <DefaultLogo />;
|
||||
|
||||
@@ -8,7 +8,6 @@ import { useState, useEffect, useMemo, type KeyboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useBufferedValue, useResetOnChange } from '@/hooks/useBufferedValue';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -21,14 +20,10 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/comp
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Combobox, type ComboboxOption } from '@/components/ui/combobox';
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
|
||||
import { Plus, X, Eye, EyeOff, Loader2, Search, Check, ChevronRight, Calendar as CalendarIcon } from 'lucide-react';
|
||||
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
|
||||
import { ExpressionEditor } from '@/components/expression/ExpressionEditor';
|
||||
import { OtpAuthField } from '@/components/forms/OtpAuthField';
|
||||
|
||||
import {
|
||||
bytesToHuman,
|
||||
humanToBytes,
|
||||
@@ -39,7 +34,13 @@ import {
|
||||
SIZE_UNITS,
|
||||
DURATION_UNITS,
|
||||
} from '@/lib/durationFormat';
|
||||
import { resolveSchema, resolveVariantForm, resolveObject, buildEmbeddedDefaults } from '@/lib/schemaResolver';
|
||||
import {
|
||||
resolveSchema,
|
||||
resolveVariantForm,
|
||||
resolveObject,
|
||||
buildEmbeddedDefaults,
|
||||
buildNewObjectValue,
|
||||
} from '@/lib/schemaResolver';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
import { useEffectiveEdition } from '@/components/forms/FormEditionContext';
|
||||
@@ -844,7 +845,7 @@ function DateTimeField({ value, onChange, readOnly, nullable }: DateTimeFieldPro
|
||||
return d && !isNaN(d.getTime()) ? d : null;
|
||||
}, [strValue]);
|
||||
|
||||
const localTime = selected ? selected.toTimeString().slice(0, 5) : '';
|
||||
const localTime = (selected ?? new Date()).toTimeString().slice(0, 5);
|
||||
|
||||
const commit = (day: Date, time: string) => {
|
||||
const [hours, minutes] = time.split(':').map(Number);
|
||||
@@ -880,7 +881,7 @@ function DateTimeField({ value, onChange, readOnly, nullable }: DateTimeFieldPro
|
||||
defaultMonth={selected ?? undefined}
|
||||
autoFocus
|
||||
onSelect={(day) => {
|
||||
if (day) commit(day, localTime || '00:00');
|
||||
if (day) commit(day, localTime);
|
||||
}}
|
||||
/>
|
||||
<div className="border-t p-3">
|
||||
@@ -1539,16 +1540,7 @@ function ObjectListField({
|
||||
|
||||
const addItem = () => {
|
||||
const nextIndex = entries.length > 0 ? Math.max(...entries.map(([k]) => parseInt(k))) + 1 : 0;
|
||||
let defaults: Record<string, unknown> = {};
|
||||
if (resolvedSchema.type === 'single' && resolvedSchema.fields.defaults) {
|
||||
defaults = { ...resolvedSchema.fields.defaults };
|
||||
} else if (resolvedSchema.type === 'multiple' && resolvedSchema.variants[0]) {
|
||||
defaults = { '@type': resolvedSchema.variants[0].name };
|
||||
if (resolvedSchema.variants[0].fields?.defaults) {
|
||||
defaults = { ...defaults, ...resolvedSchema.variants[0].fields.defaults };
|
||||
}
|
||||
}
|
||||
onChange({ ...mapValue, [String(nextIndex)]: defaults });
|
||||
onChange({ ...mapValue, [String(nextIndex)]: buildNewObjectValue(schema, objectName) });
|
||||
};
|
||||
|
||||
const removeItem = (key: string) => {
|
||||
@@ -1790,10 +1782,10 @@ function EnumMultiSelect({ enumName, items, onChange, readOnly, schema, minItems
|
||||
if (variants.length > 10) {
|
||||
const filtered = searchQuery
|
||||
? variants.filter(
|
||||
(v) =>
|
||||
v.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
v.name.toLowerCase().includes(searchQuery.toLowerCase()),
|
||||
)
|
||||
(v) =>
|
||||
v.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
v.name.toLowerCase().includes(searchQuery.toLowerCase()),
|
||||
)
|
||||
: variants;
|
||||
|
||||
return (
|
||||
@@ -2021,7 +2013,7 @@ function MapField({ keyClass, valueClass, value, onChange, readOnly, schema, min
|
||||
if (valueClass.type === 'number') {
|
||||
defaultValue = 0;
|
||||
} else if (valueClass.type === 'object') {
|
||||
defaultValue = {};
|
||||
defaultValue = buildNewObjectValue(schema, valueClass.objectName);
|
||||
}
|
||||
|
||||
onChange({ ...mapValue, [key]: defaultValue });
|
||||
|
||||
@@ -59,9 +59,7 @@ export function MainContent({ viewName, id, section }: MainContentProps) {
|
||||
|
||||
function renderView(schema: Schema | null, viewName?: string, id?: string, section?: string): ReactNode {
|
||||
if (!viewName) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8 text-muted-foreground">Select a view from the sidebar.</div>
|
||||
);
|
||||
return <LoadingFallback />;
|
||||
}
|
||||
|
||||
if (viewName.startsWith('Dashboard/')) {
|
||||
|
||||
@@ -16,13 +16,8 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/comp
|
||||
import { useUIStore } from '@/stores/uiStore';
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import {
|
||||
visibleLayouts,
|
||||
findFirstVisibleLinkInLayout,
|
||||
findFirstAccessibleLinkInLayout,
|
||||
isLinkEnterprise,
|
||||
isLinkVisible,
|
||||
} from '@/lib/layout';
|
||||
import { visibleLayouts, isLinkEnterprise, isLinkVisible } from '@/lib/layout';
|
||||
import { sectionLandingLink } from '@/lib/lastVisited';
|
||||
import type { Layout, LayoutItem, LayoutSubItem } from '@/types/schema';
|
||||
|
||||
function LucideIcon({ name, className }: { name: string; className?: string }) {
|
||||
@@ -341,9 +336,7 @@ export function Sidebar() {
|
||||
const handleSectionClick = (target: Layout) => {
|
||||
setActiveSection(target.name);
|
||||
const canGet = (prefix: string) => permissions.includes(`${prefix}Get`);
|
||||
const first =
|
||||
findFirstAccessibleLinkInLayout(schema, target, edition, canGet, hasPermission) ??
|
||||
findFirstVisibleLinkInLayout(schema, target, edition, canGet, hasPermission);
|
||||
const first = sectionLandingLink(schema, target, edition, canGet, hasPermission);
|
||||
if (first) navigate(`/${target.name}/${first}`);
|
||||
};
|
||||
|
||||
|
||||
@@ -22,7 +22,8 @@ import {
|
||||
import Logo from '@/components/common/Logo';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
|
||||
import { findFirstAccessibleLinkInLayout, findFirstVisibleLinkInLayout, visibleLayouts } from '@/lib/layout';
|
||||
import { visibleLayouts } from '@/lib/layout';
|
||||
import { sectionLandingLink } from '@/lib/lastVisited';
|
||||
import { useUIStore } from '@/stores/uiStore';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { buildEndSessionUrl, getPostLogoutRedirectUri } from '@/services/auth/oauth';
|
||||
@@ -144,9 +145,7 @@ export function TopBar() {
|
||||
onClick={() => {
|
||||
setActiveSection(layout.name);
|
||||
const canGet = (prefix: string) => hasObjectPermission(prefix, 'Get');
|
||||
const firstLink =
|
||||
findFirstAccessibleLinkInLayout(schema, layout, edition, canGet, hasPermission) ??
|
||||
findFirstVisibleLinkInLayout(schema, layout, edition, canGet, hasPermission);
|
||||
const firstLink = sectionLandingLink(schema, layout, edition, canGet, hasPermission);
|
||||
if (firstLink) {
|
||||
navigate(`/${layout.name}/${firstLink}`);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { formatSize as fmtSize, formatDuration as fmtDuration } from '@/lib/durationFormat';
|
||||
@@ -65,6 +66,8 @@ import type { Schema, Field, MassAction, ItemAction, Filter as FilterDef } from
|
||||
import type { JmapSetResponse, JmapSetError } from '@/types/jmap';
|
||||
import type { ResolvedSchema } from '@/lib/schemaResolver';
|
||||
|
||||
const ENUM_FILTER_COMBOBOX_THRESHOLD = 15;
|
||||
|
||||
const PAGE_SIZE = 25;
|
||||
const MAX_REPORTED_ERRORS = 3;
|
||||
|
||||
@@ -285,9 +288,11 @@ function renderCellValue(
|
||||
|
||||
case 'object': {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ('@type' in obj && typeof obj['@type'] === 'string') {
|
||||
return obj['@type'];
|
||||
const typeName = (value as Record<string, unknown>)['@type'];
|
||||
if (typeof typeName === 'string') {
|
||||
const objSchema = schema.schemas[ft.objectName];
|
||||
const variant = objSchema?.type === 'multiple' ? objSchema.variants.find((v) => v.name === typeName) : null;
|
||||
return <Badge variant="secondary">{variant?.label ?? typeName}</Badge>;
|
||||
}
|
||||
}
|
||||
return <span className="text-muted-foreground">-</span>;
|
||||
@@ -869,6 +874,20 @@ export function DynamicList({ viewName }: DynamicListProps) {
|
||||
|
||||
case 'enum': {
|
||||
const enumVariants = schema!.enums[filterDef.enumName] ?? [];
|
||||
if (enumVariants.length > ENUM_FILTER_COMBOBOX_THRESHOLD) {
|
||||
return wrapper(
|
||||
<Combobox
|
||||
options={[
|
||||
{ value: '__all__', label: t('filters.all', 'All') },
|
||||
...enumVariants.map((v) => ({ value: v.name, label: v.label })),
|
||||
]}
|
||||
value={value || '__all__'}
|
||||
onValueChange={(v) => handleFilterSelectChange(filterDef.field, v)}
|
||||
searchPlaceholder={t('common.searchPlaceholder', 'Search...')}
|
||||
emptyText={t('field.noMatches', 'No matches')}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
return wrapper(
|
||||
<Select value={value || '__all__'} onValueChange={(v) => handleFilterSelectChange(filterDef.field, v)}>
|
||||
<SelectTrigger>
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import {
|
||||
findFirstAccessibleLinkInLayout,
|
||||
findFirstVisibleLinkInLayout,
|
||||
isLinkAccessible,
|
||||
type CanGet,
|
||||
type HasPermission,
|
||||
} from '@/lib/layout';
|
||||
import type { Layout, Schema } from '@/types/schema';
|
||||
|
||||
const STORAGE_KEY = 'stalwart-last-visited';
|
||||
|
||||
function readAll(): Record<string, unknown> {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : null;
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberLastVisited(section: string, viewName: string): void {
|
||||
try {
|
||||
const all = readAll();
|
||||
if (all[section] === viewName) return;
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...all, [section]: viewName }));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export function sectionLandingLink(
|
||||
schema: Schema,
|
||||
layout: Layout,
|
||||
edition: string,
|
||||
canGet: CanGet,
|
||||
hasPerm?: HasPermission,
|
||||
): string | null {
|
||||
const last = readAll()[layout.name];
|
||||
if (typeof last === 'string' && isLinkAccessible(schema, last, edition, canGet, hasPerm)) {
|
||||
return last;
|
||||
}
|
||||
return (
|
||||
findFirstAccessibleLinkInLayout(schema, layout, edition, canGet, hasPerm) ??
|
||||
findFirstVisibleLinkInLayout(schema, layout, edition, canGet, hasPerm)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { getApiBaseUrl } from '@/services/api';
|
||||
|
||||
export type LogoState = { status: 'loading' } | { status: 'custom'; url: string } | { status: 'default' };
|
||||
|
||||
let state: LogoState = { status: 'loading' };
|
||||
let started = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export function getLogoState(): LogoState {
|
||||
return state;
|
||||
}
|
||||
|
||||
export function subscribeToLogo(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function loadLogoOnce(): void {
|
||||
if (started) return;
|
||||
started = true;
|
||||
fetch(`${getApiBaseUrl()}/logo`)
|
||||
.then(async (response) => {
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (!response.ok || !contentType.startsWith('image/')) return null;
|
||||
return URL.createObjectURL(await response.blob());
|
||||
})
|
||||
.catch(() => null)
|
||||
.then((url) => {
|
||||
state = url ? { status: 'custom', url } : { status: 'default' };
|
||||
listeners.forEach((notify) => notify());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { describe, it, expect, afterEach, vi } from 'vitest';
|
||||
|
||||
const originalHead = document.head.innerHTML;
|
||||
|
||||
async function loadWithMeta(meta: string) {
|
||||
document.head.innerHTML = meta;
|
||||
vi.resetModules();
|
||||
const { getOAuthClientId } = await import('./oauthClientId');
|
||||
return getOAuthClientId;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.head.innerHTML = originalHead;
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
describe('getOAuthClientId', () => {
|
||||
it('prefers the client id injected by the server', async () => {
|
||||
const getOAuthClientId = await loadWithMeta('<meta name="oauth-client-id" content="pocket-id-client" />');
|
||||
expect(getOAuthClientId()).toBe('pocket-id-client');
|
||||
});
|
||||
|
||||
it('trims surrounding whitespace from the injected client id', async () => {
|
||||
const getOAuthClientId = await loadWithMeta('<meta name="oauth-client-id" content=" pocket-id-client " />');
|
||||
expect(getOAuthClientId()).toBe('pocket-id-client');
|
||||
});
|
||||
|
||||
it('falls back to the built-in default when the placeholder is empty', async () => {
|
||||
const getOAuthClientId = await loadWithMeta('<meta name="oauth-client-id" content="" />');
|
||||
expect(getOAuthClientId()).toBe('stalwart-webui');
|
||||
});
|
||||
|
||||
it('falls back to the built-in default when the placeholder is only whitespace', async () => {
|
||||
const getOAuthClientId = await loadWithMeta('<meta name="oauth-client-id" content=" " />');
|
||||
expect(getOAuthClientId()).toBe('stalwart-webui');
|
||||
});
|
||||
|
||||
it('falls back to the built-in default when the placeholder is absent', async () => {
|
||||
const getOAuthClientId = await loadWithMeta('');
|
||||
expect(getOAuthClientId()).toBe('stalwart-webui');
|
||||
});
|
||||
|
||||
it('reads the document only once', async () => {
|
||||
const getOAuthClientId = await loadWithMeta('<meta name="oauth-client-id" content="pocket-id-client" />');
|
||||
expect(getOAuthClientId()).toBe('pocket-id-client');
|
||||
|
||||
document.head.innerHTML = '<meta name="oauth-client-id" content="changed-later" />';
|
||||
expect(getOAuthClientId()).toBe('pocket-id-client');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
const DEFAULT_CLIENT_ID = 'stalwart-webui';
|
||||
|
||||
let cached: string | undefined;
|
||||
|
||||
export function getOAuthClientId(): string {
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
const injected = document.querySelector('meta[name="oauth-client-id"]')?.getAttribute('content')?.trim();
|
||||
cached = injected ? injected : DEFAULT_CLIENT_ID;
|
||||
return cached;
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
deepMerge,
|
||||
buildCreateDefaults,
|
||||
buildEmbeddedDefaults,
|
||||
buildNewObjectValue,
|
||||
} from './schemaResolver';
|
||||
import { getDisplayProperty } from './schemaResolver';
|
||||
|
||||
@@ -865,3 +866,115 @@ describe('getDisplayProperty', () => {
|
||||
expect(getDisplayProperty(schema, 'x:NoLabel')).toBe('title');
|
||||
});
|
||||
});
|
||||
|
||||
const structSchema: Schema = {
|
||||
objects: {},
|
||||
schemas: {
|
||||
'x:Service': { type: 'single', schemaName: 'x:Service' },
|
||||
'x:Listener': { type: 'single', schemaName: 'x:Listener' },
|
||||
'x:Tls': { type: 'single', schemaName: 'x:Tls' },
|
||||
'x:Store': {
|
||||
type: 'multiple',
|
||||
variants: [
|
||||
{ name: 'S3', label: 'S3', schemaName: 'x:S3Store' },
|
||||
{ name: 'Manual', label: 'Manual' },
|
||||
],
|
||||
},
|
||||
},
|
||||
fields: {
|
||||
'x:Service': {
|
||||
properties: {
|
||||
hostname: {
|
||||
description: '',
|
||||
type: { type: 'string', format: 'string', nullable: true },
|
||||
update: 'mutable',
|
||||
},
|
||||
cleartext: { description: '', type: { type: 'boolean' }, update: 'mutable' },
|
||||
},
|
||||
},
|
||||
'x:Listener': {
|
||||
properties: {
|
||||
enabled: { description: '', type: { type: 'boolean' }, update: 'mutable' },
|
||||
proxied: { description: '', type: { type: 'boolean' }, update: 'mutable' },
|
||||
readOnly: { description: '', type: { type: 'boolean' }, update: 'serverSet' },
|
||||
tls: { description: '', type: { type: 'object', objectName: 'x:Tls' }, update: 'mutable' },
|
||||
fallback: {
|
||||
description: '',
|
||||
type: { type: 'object', objectName: 'x:Tls', nullable: true },
|
||||
update: 'mutable',
|
||||
},
|
||||
},
|
||||
defaults: {
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
'x:Tls': {
|
||||
properties: {
|
||||
implicit: { description: '', type: { type: 'boolean' }, update: 'mutable' },
|
||||
certificateId: {
|
||||
description: '',
|
||||
type: { type: 'string', format: 'string', nullable: true },
|
||||
update: 'mutable',
|
||||
},
|
||||
},
|
||||
},
|
||||
'x:S3Store': {
|
||||
properties: {
|
||||
bucket: { description: '', type: { type: 'string', format: 'string' }, update: 'mutable' },
|
||||
allowInvalidCerts: { description: '', type: { type: 'boolean' }, update: 'mutable' },
|
||||
},
|
||||
defaults: {
|
||||
bucket: 'stalwart',
|
||||
},
|
||||
},
|
||||
},
|
||||
forms: {},
|
||||
lists: {},
|
||||
enums: {},
|
||||
dashboards: [],
|
||||
layouts: [],
|
||||
};
|
||||
|
||||
describe('buildNewObjectValue', () => {
|
||||
it('seeds non-nullable booleans a struct has no defaults for', () => {
|
||||
expect(buildNewObjectValue(structSchema, 'x:Service')).toEqual({ cleartext: false });
|
||||
});
|
||||
|
||||
it('keeps schema defaults and only fills the missing booleans', () => {
|
||||
const result = buildNewObjectValue(structSchema, 'x:Listener');
|
||||
expect(result.enabled).toBe(true);
|
||||
expect(result.proxied).toBe(false);
|
||||
});
|
||||
|
||||
it('skips serverSet properties', () => {
|
||||
expect(buildNewObjectValue(structSchema, 'x:Listener')).not.toHaveProperty('readOnly');
|
||||
});
|
||||
|
||||
it('recurses into non-nullable embedded objects and skips nullable ones', () => {
|
||||
const result = buildNewObjectValue(structSchema, 'x:Listener');
|
||||
expect(result.tls).toEqual({ implicit: false });
|
||||
expect(result).not.toHaveProperty('fallback');
|
||||
});
|
||||
|
||||
it('seeds the first variant with its @type, defaults and booleans', () => {
|
||||
expect(buildNewObjectValue(structSchema, 'x:Store')).toEqual({
|
||||
'@type': 'S3',
|
||||
bucket: 'stalwart',
|
||||
allowInvalidCerts: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('honours an explicit variant name', () => {
|
||||
expect(buildNewObjectValue(structSchema, 'x:Store', 'Manual')).toEqual({ '@type': 'Manual' });
|
||||
});
|
||||
|
||||
it('returns an empty object for an unknown object name', () => {
|
||||
expect(buildNewObjectValue(structSchema, 'x:Unknown')).toEqual({});
|
||||
});
|
||||
|
||||
it('still merges parent defaults into embedded children', () => {
|
||||
const result = buildNewObjectValue(embeddedSchema, 'x:Model', 'FtrlCcfh');
|
||||
expect(result.featureL2Normalize).toBe(true);
|
||||
expect((result.parameters as Record<string, unknown>).numFeatures).toBe('20');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -260,6 +260,62 @@ export function buildEmbeddedDefaults(
|
||||
return result;
|
||||
}
|
||||
|
||||
export function buildNewObjectValue(schema: Schema, objectName: string, variantName?: string): Record<string, unknown> {
|
||||
const result = buildEmbeddedDefaults(schema, objectName, {}, variantName);
|
||||
return completeStructDefaults(schema, objectName, (result['@type'] as string | undefined) ?? variantName, result);
|
||||
}
|
||||
|
||||
function completeStructDefaults(
|
||||
schema: Schema,
|
||||
objectName: string,
|
||||
variantName: string | undefined,
|
||||
target: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const resolved = resolveSchema(schema, objectName);
|
||||
if (!resolved) return target;
|
||||
|
||||
const fields =
|
||||
resolved.type === 'single'
|
||||
? resolved.fields
|
||||
: ((variantName ? resolved.variants.find((v) => v.name === variantName) : resolved.variants[0])?.fields ?? null);
|
||||
if (!fields) return target;
|
||||
|
||||
for (const [propName, propDef] of Object.entries(fields.properties)) {
|
||||
if (propDef.update === 'serverSet') continue;
|
||||
const t = propDef.type;
|
||||
|
||||
if (t.type === 'boolean') {
|
||||
if (!(propName in target)) {
|
||||
target[propName] = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (t.type !== 'object' || t.nullable) continue;
|
||||
|
||||
const current = target[propName];
|
||||
if (current !== undefined && !isPlainRecord(current)) continue;
|
||||
|
||||
const overrides = isPlainRecord(current) ? current : {};
|
||||
const nestedEntry = schema.schemas[t.objectName];
|
||||
const nestedVariant =
|
||||
nestedEntry?.type === 'multiple'
|
||||
? ((overrides['@type'] as string | undefined) ?? nestedEntry.variants[0]?.name)
|
||||
: undefined;
|
||||
|
||||
const nested = completeStructDefaults(schema, t.objectName, nestedVariant, { ...overrides });
|
||||
if (Object.keys(nested).length > 0) {
|
||||
target[propName] = nested;
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function getDisplayProperty(schema: Schema, objectName: string): string {
|
||||
const list = schema.lists[objectName];
|
||||
if (list?.labelProperty) return list.labelProperty;
|
||||
|
||||
@@ -16,6 +16,7 @@ import NotFound from './pages/NotFound';
|
||||
import { AdminPanel } from './pages/AdminPanel.lazy';
|
||||
import { ProtectedRoute } from './components/layout/ProtectedRoute';
|
||||
import { getBasePath } from './lib/basePath';
|
||||
import { loadLogoOnce } from './lib/logoCache';
|
||||
|
||||
(() => {
|
||||
try {
|
||||
@@ -34,6 +35,8 @@ import { getBasePath } from './lib/basePath';
|
||||
document.documentElement.classList.toggle('dark', !!prefersDark);
|
||||
})();
|
||||
|
||||
loadLogoOnce();
|
||||
|
||||
const basePath = getBasePath();
|
||||
|
||||
const router = createBrowserRouter(
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
import { usePermissions } from '@/hooks/usePermissions';
|
||||
import { useDocumentTitle } from '@/hooks/useDocumentTitle';
|
||||
import { friendlyName } from '@/hooks/useGlobalSearch';
|
||||
import { rememberLastVisited, sectionLandingLink } from '@/lib/lastVisited';
|
||||
|
||||
const BootstrapWizard = lazy(() =>
|
||||
import('@/components/bootstrap/BootstrapWizard').then((m) => ({ default: m.BootstrapWizard })),
|
||||
@@ -210,15 +211,13 @@ export default function AdminPanel() {
|
||||
if (section && viewName) {
|
||||
const ownLayout = layouts.find((l) => l.name.toLowerCase() === section.toLowerCase());
|
||||
setActiveSection(ownLayout?.name ?? layouts[0]?.name ?? section);
|
||||
if (ownLayout) rememberLastVisited(ownLayout.name, viewName);
|
||||
return;
|
||||
}
|
||||
|
||||
if (section) {
|
||||
const ownLayout = layouts.find((l) => l.name.toLowerCase() === section.toLowerCase());
|
||||
const ownLink = ownLayout
|
||||
? (findFirstAccessibleLinkInLayout(schema, ownLayout, edition, canGet, hasPerm) ??
|
||||
findFirstVisibleLinkInLayout(schema, ownLayout, edition, canGet, hasPerm))
|
||||
: null;
|
||||
const ownLink = ownLayout ? sectionLandingLink(schema, ownLayout, edition, canGet, hasPerm) : null;
|
||||
if (ownLayout && ownLink) {
|
||||
redirectTo(ownLayout.name, ownLink);
|
||||
} else {
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@
|
||||
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import { getBasePath } from '@/lib/basePath';
|
||||
import { getOAuthClientId } from '@/lib/oauthClientId';
|
||||
|
||||
export function getApiBaseUrl(): string {
|
||||
const envUrl = import.meta.env.VITE_API_BASE_URL as string | undefined;
|
||||
@@ -45,7 +46,7 @@ export async function refreshAccessToken(): Promise<void> {
|
||||
throw new Error('No refresh token or token endpoint available');
|
||||
}
|
||||
|
||||
const clientId = (import.meta.env.VITE_OAUTH_CLIENT_ID as string) || 'stalwart-webui';
|
||||
const clientId = getOAuthClientId();
|
||||
|
||||
try {
|
||||
const response = await fetch(tokenEndpoint, {
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
import { getApiBaseUrl } from '@/services/api';
|
||||
import { getBasePath } from '@/lib/basePath';
|
||||
import { getOAuthClientId } from '@/lib/oauthClientId';
|
||||
import i18n from '@/i18n';
|
||||
|
||||
const CLIENT_ID = (import.meta.env.VITE_OAUTH_CLIENT_ID as string) || 'stalwart-webui';
|
||||
const SCOPES = import.meta.env.VITE_OAUTH_SCOPES as string | undefined;
|
||||
|
||||
const SESSION_PREFIX = 'stalwart-oauth-';
|
||||
@@ -97,7 +97,7 @@ export async function exchangeCode(
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
code_verifier: codeVerifier,
|
||||
client_id: CLIENT_ID,
|
||||
client_id: getOAuthClientId(),
|
||||
redirect_uri: redirectUri,
|
||||
});
|
||||
|
||||
@@ -153,7 +153,7 @@ export async function startAuthFlow(username: string, returnUrl?: string | null)
|
||||
|
||||
const params = new URLSearchParams({
|
||||
response_type: 'code',
|
||||
client_id: CLIENT_ID,
|
||||
client_id: getOAuthClientId(),
|
||||
redirect_uri: getRedirectUri(),
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: codeChallengeMethod,
|
||||
@@ -206,7 +206,7 @@ export function getPostLogoutRedirectUri(): string {
|
||||
|
||||
export function buildEndSessionUrl(endSessionEndpoint: string, postLogoutRedirectUri: string): string {
|
||||
const params = new URLSearchParams({
|
||||
client_id: CLIENT_ID,
|
||||
client_id: getOAuthClientId(),
|
||||
post_logout_redirect_uri: postLogoutRedirectUri,
|
||||
});
|
||||
const sep = endSessionEndpoint.includes('?') ? '&' : '?';
|
||||
|
||||
Vendored
-1
@@ -8,7 +8,6 @@
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_BASE_URL: string;
|
||||
readonly VITE_OAUTH_CLIENT_ID: string;
|
||||
readonly VITE_ACCESS_TOKEN: string;
|
||||
readonly VITE_OAUTH_SCOPES: string;
|
||||
readonly VITE_DEBUG_JMAP?: string;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/// <reference types="vitest/config" />
|
||||
import { configDefaults } from 'vitest/config'
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
@@ -19,5 +20,6 @@ export default defineConfig({
|
||||
test: {
|
||||
globals: false,
|
||||
environment: 'happy-dom',
|
||||
exclude: [...configDefaults.exclude, '**/.ignore/**'],
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user