Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc462b137f | ||
|
|
b0b8e4e090 | ||
|
|
af11f5119c |
@@ -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,33 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [1.0.11] - 2026-09-15
|
||||
|
||||
### Added
|
||||
- Sievepad integration.
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
|
||||
## [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
|
||||
|
||||
@@ -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>
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"private": true,
|
||||
"version": "1.0.8",
|
||||
"version": "1.0.11",
|
||||
"description": "Stalwart WebUI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -26,12 +26,20 @@ export function EnterpriseUpsell({ open, onClose }: EnterpriseUpsellProps) {
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogContent className="gap-6">
|
||||
<DialogHeader className="space-y-4">
|
||||
<DialogTitle>{t('enterprise.trialTitle')}</DialogTitle>
|
||||
<DialogDescription>{t('enterprise.trialDescription')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<DialogFooter className="gap-2 sm:items-center">
|
||||
<a
|
||||
href="https://stalw.art/compare#why-isnt-feature-x-open-source"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-center text-xs text-muted-foreground underline-offset-4 hover:underline sm:mr-auto sm:text-left"
|
||||
>
|
||||
{t('enterprise.whyNotFree')}
|
||||
</a>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
{t('common.close')}
|
||||
</Button>
|
||||
|
||||
@@ -53,6 +53,7 @@ import { SECRET_MASK } from '@/lib/jmapUtils';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { logFormChange } from '@/lib/debug';
|
||||
import { FieldWidget } from '@/components/forms/FieldWidget';
|
||||
import { isSieveScriptField } from '@/lib/sievepad';
|
||||
|
||||
import type { Field, Fields, Form, FormField, Schema } from '@/types/schema';
|
||||
import type { JmapSetResponse, JmapSetError, JmapMethodCall } from '@/types/jmap';
|
||||
@@ -740,6 +741,7 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
})();
|
||||
|
||||
const sectionsToRender = buildSections(combinedForm, currentFields, isCreate, edition);
|
||||
const scriptName = typeof formData.name === 'string' ? formData.name : '';
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl space-y-6">
|
||||
@@ -810,6 +812,9 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
readOnly={fieldReadOnly}
|
||||
error={fieldError}
|
||||
schema={schema}
|
||||
sieveScriptName={
|
||||
isSieveScriptField(resolved.obj.objectName, formField.name) ? scriptName : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
@@ -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,11 @@ 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 { SievepadButton } from '@/components/forms/SievepadButton';
|
||||
import {
|
||||
bytesToHuman,
|
||||
humanToBytes,
|
||||
@@ -39,7 +35,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';
|
||||
@@ -58,6 +60,7 @@ export interface FieldWidgetProps {
|
||||
readOnly: boolean;
|
||||
error?: string;
|
||||
schema: Schema;
|
||||
sieveScriptName?: string;
|
||||
}
|
||||
|
||||
function getRequiredMarker(field: Field, readOnly: boolean): 'required' | 'optional' | null {
|
||||
@@ -78,7 +81,7 @@ function getRequiredMarker(field: Field, readOnly: boolean): 'required' | 'optio
|
||||
|
||||
export function FieldWidget(props: FieldWidgetProps) {
|
||||
const { t } = useTranslation();
|
||||
const { field, formField, value, onChange, readOnly, error, schema } = props;
|
||||
const { field, formField, value, onChange, readOnly, error, schema, sieveScriptName } = props;
|
||||
const ft = field.type;
|
||||
const edition = useEffectiveEdition();
|
||||
|
||||
@@ -131,7 +134,7 @@ export function FieldWidget(props: FieldWidgetProps) {
|
||||
/>
|
||||
);
|
||||
case 'blobId':
|
||||
return <BlobField value={value} onChange={onChange} readOnly={readOnly} />;
|
||||
return <BlobField value={value} onChange={onChange} readOnly={readOnly} sieveScriptName={sieveScriptName} />;
|
||||
case 'objectId':
|
||||
return (
|
||||
<ObjectIdField
|
||||
@@ -235,6 +238,9 @@ export function FieldWidget(props: FieldWidgetProps) {
|
||||
</div>
|
||||
)}
|
||||
{widget}
|
||||
{sieveScriptName !== undefined && ft.type === 'string' && (
|
||||
<SievepadButton scriptName={sieveScriptName} source={typeof value === 'string' ? value : ''} />
|
||||
)}
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
@@ -985,9 +991,10 @@ interface BlobFieldProps {
|
||||
value: unknown;
|
||||
onChange: (value: unknown) => void;
|
||||
readOnly: boolean;
|
||||
sieveScriptName?: string;
|
||||
}
|
||||
|
||||
function BlobField({ value, onChange, readOnly }: BlobFieldProps) {
|
||||
function BlobField({ value, onChange, readOnly, sieveScriptName }: BlobFieldProps) {
|
||||
const { t } = useTranslation();
|
||||
const blobId = typeof value === 'string' ? value : null;
|
||||
const [content, setContent] = useState<string>('');
|
||||
@@ -1053,6 +1060,7 @@ function BlobField({ value, onChange, readOnly }: BlobFieldProps) {
|
||||
rows={8}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
{sieveScriptName !== undefined && <SievepadButton scriptName={sieveScriptName} source={content} />}
|
||||
{modified && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('field.contentModified', 'Content modified (will be saved as a new blob)')}
|
||||
@@ -1539,16 +1547,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) => {
|
||||
@@ -2021,7 +2020,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 });
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bug } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { dismissSievepadWarning, isSievepadWarningDismissed, openInSievepad } from '@/lib/sievepad';
|
||||
|
||||
interface SievepadButtonProps {
|
||||
scriptName: string;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const [warningOpen, setWarningOpen] = useState(false);
|
||||
const [dontShowAgain, setDontShowAgain] = useState(false);
|
||||
|
||||
const open = () => {
|
||||
openInSievepad(scriptName || t('sievepad.defaultName', 'Sieve script'), source).catch(() => {
|
||||
toast({ title: t('sievepad.failed', 'Failed to open Sievepad.'), variant: 'destructive' });
|
||||
});
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
if (isSievepadWarningDismissed()) {
|
||||
open();
|
||||
} else {
|
||||
setDontShowAgain(false);
|
||||
setWarningOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
if (dontShowAgain) dismissSievepadWarning();
|
||||
setWarningOpen(false);
|
||||
open();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleClick} disabled={!source.trim()}>
|
||||
<Bug className="h-4 w-4" />
|
||||
{t('sievepad.debug', 'Debug')}
|
||||
</Button>
|
||||
</div>
|
||||
<Dialog open={warningOpen} onOpenChange={setWarningOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('sievepad.warningTitle', 'Debug in Sievepad')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(
|
||||
'sievepad.warningDescription',
|
||||
'A new tab will open sievepad.com with a copy of this script. Sievepad compiles and runs the script entirely in your browser: nothing is uploaded to or stored on any server.',
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="sievepad-dont-show-again"
|
||||
checked={dontShowAgain}
|
||||
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="sievepad-dont-show-again" className="text-sm font-normal">
|
||||
{t('sievepad.dontShowAgain', "Don't show this again")}
|
||||
</Label>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setWarningOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button type="button" onClick={handleContinue}>
|
||||
{t('common.continue')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+10
-1
@@ -136,7 +136,8 @@
|
||||
"trialDescription": "Get access to advanced features including multi-tenancy, AI-powered spam filtering, alerts, and more.",
|
||||
"trialButton": "Start 30-Day Free Trial",
|
||||
"requestTrial": "Request a free trial to unlock this feature.",
|
||||
"ossHidden": "This feature is not available in the open-source edition."
|
||||
"ossHidden": "This feature is not available in the open-source edition.",
|
||||
"whyNotFree": "Why is this not free?"
|
||||
},
|
||||
"errorBoundary": {
|
||||
"title": "Something went wrong",
|
||||
@@ -340,6 +341,14 @@
|
||||
"periodValue": "Period value"
|
||||
},
|
||||
"sections": "Sections",
|
||||
"sievepad": {
|
||||
"debug": "Debug",
|
||||
"defaultName": "Sieve script",
|
||||
"dontShowAgain": "Don't show this again",
|
||||
"failed": "Failed to open Sievepad.",
|
||||
"warningDescription": "A new tab will open sievepad.com with a copy of this script. Sievepad compiles and runs the script entirely in your browser: nothing is uploaded to or stored on any server.",
|
||||
"warningTitle": "Debug in Sievepad"
|
||||
},
|
||||
"toggleTheme": "Toggle theme",
|
||||
"tracing": {
|
||||
"addFilter": "Add filter",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { inflateRawSync } from 'node:zlib';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { SIEVEPAD_URL, isSieveScriptField, sievepadLink } from './sievepad';
|
||||
|
||||
function decode(link: string): unknown {
|
||||
const token = new URLSearchParams(new URL(link).hash.slice(1)).get('w') ?? '';
|
||||
return JSON.parse(inflateRawSync(Buffer.from(token, 'base64url')).toString('utf8'));
|
||||
}
|
||||
|
||||
describe('sievepadLink', () => {
|
||||
it('encodes the script as a single main entry', async () => {
|
||||
const source = 'require "imap4flags";\r\naddflag "\\\\Seen";\r\n';
|
||||
const link = await sievepadLink('Filters é', source);
|
||||
|
||||
expect(link.startsWith(`${SIEVEPAD_URL}#w=`)).toBe(true);
|
||||
expect(link.slice(`${SIEVEPAD_URL}#w=`.length)).toMatch(/^[A-Za-z0-9_-]+$/);
|
||||
expect(decode(link)).toEqual({
|
||||
v: 1,
|
||||
name: 'Filters é',
|
||||
scripts: [{ name: 'main', source: 'require "imap4flags";\naddflag "\\\\Seen";\n' }],
|
||||
messages: [],
|
||||
settings: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('truncates long workspace names', async () => {
|
||||
const link = await sievepadLink('x'.repeat(200), 'keep;');
|
||||
expect((decode(link) as { name: string }).name).toHaveLength(80);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSieveScriptField', () => {
|
||||
it('matches only the known script fields', () => {
|
||||
expect(isSieveScriptField('x:SieveUserScript', 'contents')).toBe(true);
|
||||
expect(isSieveScriptField('x:SieveSystemScript', 'contents')).toBe(true);
|
||||
expect(isSieveScriptField('SieveScript', 'blobId')).toBe(true);
|
||||
expect(isSieveScriptField('SieveScript', 'name')).toBe(false);
|
||||
expect(isSieveScriptField('x:Domain', 'contents')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
export const SIEVEPAD_URL = 'https://sievepad.com/';
|
||||
|
||||
const SIEVEPAD_FORMAT_VERSION = 1;
|
||||
const SIEVEPAD_MAX_NAME_LENGTH = 80;
|
||||
const SIEVEPAD_MAIN_SCRIPT = 'main';
|
||||
const BASE64_CHUNK_SIZE = 0x8000;
|
||||
const WARNING_DISMISSED_KEY = 'stalwart-sievepad-warning-dismissed';
|
||||
|
||||
const SIEVE_SCRIPT_FIELDS: Record<string, string> = {
|
||||
'x:SieveSystemScript': 'contents',
|
||||
'x:SieveUserScript': 'contents',
|
||||
SieveScript: 'blobId',
|
||||
};
|
||||
|
||||
export function isSieveScriptField(objectName: string, fieldName: string): boolean {
|
||||
return SIEVE_SCRIPT_FIELDS[objectName] === fieldName;
|
||||
}
|
||||
|
||||
function toBase64Url(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK_SIZE));
|
||||
}
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
export async function sievepadLink(name: string, source: string, base = SIEVEPAD_URL): Promise<string> {
|
||||
const json = JSON.stringify({
|
||||
v: SIEVEPAD_FORMAT_VERSION,
|
||||
name: name.slice(0, SIEVEPAD_MAX_NAME_LENGTH),
|
||||
scripts: [{ name: SIEVEPAD_MAIN_SCRIPT, source: source.replace(/\r\n/g, '\n') }],
|
||||
messages: [],
|
||||
settings: {},
|
||||
});
|
||||
const stream = new Blob([new TextEncoder().encode(json)]).stream().pipeThrough(new CompressionStream('deflate-raw'));
|
||||
const packed = new Uint8Array(await new Response(stream).arrayBuffer());
|
||||
return `${base}#w=${toBase64Url(packed)}`;
|
||||
}
|
||||
|
||||
export async function openInSievepad(name: string, source: string): Promise<void> {
|
||||
const tab = window.open('about:blank', '_blank');
|
||||
if (tab) tab.opener = null;
|
||||
let link: string;
|
||||
try {
|
||||
link = await sievepadLink(name, source);
|
||||
} catch (err) {
|
||||
tab?.close();
|
||||
throw err;
|
||||
}
|
||||
if (tab) {
|
||||
tab.location.replace(link);
|
||||
} else {
|
||||
window.open(link, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
}
|
||||
|
||||
export function isSievepadWarningDismissed(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(WARNING_DISMISSED_KEY) === 'true';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function dismissSievepadWarning(): void {
|
||||
try {
|
||||
localStorage.setItem(WARNING_DISMISSED_KEY, 'true');
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
+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;
|
||||
|
||||
Reference in New Issue
Block a user