4 Commits
17 changed files with 132 additions and 387 deletions

No files matched your search

+19
View File
@@ -2,6 +2,25 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
## [2.0.3] - 2026-10-29
### Added
### Changed
- Logging out no longer revokes the OAuth tokens.
### Fixed
- OAuth sign-in sends the RFC 8707 `resource` parameter in the authorization request, the code exchange and token refreshes, so external identity providers that require an audience or scopes issue tokens the server accepts.
## [2.0.2] - 2026-10-28
### Added
### Changed
- Object pickers in forms are now scoped to the tenant of the record being edited: for objects that belong to a tenant (`memberTenantId`), only options from the same tenant are offered.
### Fixed
## [2.0.1] - 2026-10-27
### Added
+3 -264
View File
@@ -1,12 +1,12 @@
{
"name": "stalwart-webui",
"version": "2.0.1",
"version": "2.0.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "stalwart-webui",
"version": "2.0.1",
"version": "2.0.3",
"dependencies": {
"@daypicker/react": "^10.0.2",
"@noble/hashes": "^2.4.0",
@@ -64,8 +64,7 @@
"tw-animate-css": "^1.4.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.71.2",
"vite": "^8.3.4",
"vitest": "5.0.3"
"vite": "^8.3.4"
}
},
"node_modules/@babel/code-frame": {
@@ -2709,17 +2708,6 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/deep-eql": "*",
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
@@ -2792,13 +2780,6 @@
"@types/ms": "*"
}
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/esrecurse": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
@@ -3180,54 +3161,6 @@
}
}
},
"node_modules/@vitest/mocker": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz",
"integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "0.3.31",
"@vitest/spy": "5.0.3",
"estree-walker": "^3.0.3",
"magic-string": "^1.2.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
}
},
"node_modules/@vitest/mocker/node_modules/magic-string": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
"integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.6.0"
}
},
"node_modules/@vitest/spy": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz",
"integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/acorn": {
"version": "8.17.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
@@ -3304,16 +3237,6 @@
"node": ">=10"
}
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/babel-plugin-react-compiler": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/babel-plugin-react-compiler/-/babel-plugin-react-compiler-1.0.0.tgz",
@@ -3458,16 +3381,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/chai": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
"integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/character-entities": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
@@ -3892,13 +3805,6 @@
"node": ">=10.13.0"
}
},
"node_modules/es-module-lexer": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
"integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
"dev": true,
"license": "MIT"
},
"node_modules/es-toolkit": {
"version": "1.45.1",
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.45.1.tgz",
@@ -4133,16 +4039,6 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
}
},
"node_modules/esutils": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
@@ -4159,16 +4055,6 @@
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
@@ -5678,20 +5564,6 @@
"node": ">=18"
}
},
"node_modules/obug": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
"integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
"dev": true,
"funding": [
"https://github.com/sponsors/sxzz",
"https://opencollective.com/debug"
],
"license": "MIT",
"engines": {
"node": ">=12.20.0"
}
},
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -6476,13 +6348,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/std-env": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
"integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
"dev": true,
"license": "MIT"
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
@@ -6591,26 +6456,6 @@
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
"license": "MIT"
},
"node_modules/tinybench": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz",
"integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/tinyexec": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
"integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -7315,99 +7160,6 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/vitest": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz",
"integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/mocker": "5.0.3",
"chai": "^6.2.2",
"es-module-lexer": "^2.3.2",
"expect-type": "^1.4.0",
"magic-string": "^1.2.3",
"obug": "^2.1.4",
"picomatch": "^4.0.7",
"std-env": "^4.2.0",
"tinybench": "^6.1.4",
"tinyexec": "^1.3.0",
"tinyglobby": "^0.2.17",
"why-is-node-running": "3.2.1"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
"@opentelemetry/api": "^1.9.0",
"@types/node": "^22.0.0 || >=24.0.0",
"@vitest/browser-playwright": "5.0.3",
"@vitest/browser-preview": "5.0.3",
"@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
"@vitest/coverage-istanbul": "5.0.3",
"@vitest/coverage-v8": "5.0.3",
"@vitest/ui": "5.0.3",
"happy-dom": "*",
"jsdom": "*",
"vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"@edge-runtime/vm": {
"optional": true
},
"@opentelemetry/api": {
"optional": true
},
"@types/node": {
"optional": true
},
"@vitest/browser-playwright": {
"optional": true
},
"@vitest/browser-preview": {
"optional": true
},
"@vitest/browser-webdriverio": {
"optional": true
},
"@vitest/coverage-istanbul": {
"optional": true
},
"@vitest/coverage-v8": {
"optional": true
},
"@vitest/ui": {
"optional": true
},
"happy-dom": {
"optional": true
},
"jsdom": {
"optional": true
},
"vite": {
"optional": false
}
}
},
"node_modules/vitest/node_modules/magic-string": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
"integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.6.0"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -7430,19 +7182,6 @@
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
"license": "ISC"
},
"node_modules/why-is-node-running": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz",
"integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==",
"dev": true,
"license": "MIT",
"bin": {
"why-is-node-running": "cli.js"
},
"engines": {
"node": ">=20.11"
}
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
+2 -4
View File
@@ -1,7 +1,7 @@
{
"name": "stalwart-webui",
"private": true,
"version": "2.0.1",
"version": "2.0.3",
"stalwart": {
"minServerVersion": "1.0.0"
},
@@ -12,7 +12,6 @@
"build": "tsc -b && vite build",
"typecheck": "tsc -p tsconfig.app.json --noEmit",
"lint": "eslint .",
"test": "vitest run",
"preview": "vite preview",
"format": "prettier --write src/",
"format:check": "prettier --check src/"
@@ -74,7 +73,6 @@
"tw-animate-css": "^1.4.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.71.2",
"vite": "^8.3.4",
"vitest": "5.0.3"
"vite": "^8.3.4"
}
}
+3
View File
@@ -12,6 +12,7 @@ import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { useCanAccess } from '@/hooks/usePermissions';
import { coerceLabel } from '@/lib/objectOptions';
import { TENANT_PROPERTY } from '@/lib/schemaResolver';
import { CreatedValuesDialog } from '@/components/forms/CreatedValuesDialog';
import { FormProvider } from '@/components/forms/FormProvider';
import { FormSections } from '@/components/forms/FormSections';
@@ -108,6 +109,7 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
t('form.item', 'item')
).toLowerCase();
const sch = resolved.resolvedSchema;
const tenantValue = state.data[TENANT_PROPERTY];
return (
<div className="mx-auto max-w-4xl space-y-6">
@@ -125,6 +127,7 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
readOnly={readOnly}
recordLabel={model.recordLabel}
baseline={state.original}
tenantId={typeof tenantValue === 'string' ? tenantValue : null}
>
<FormSections
sections={model.sections}
+3
View File
@@ -23,6 +23,7 @@ interface FormProviderProps {
hideEnterprise?: boolean;
recordLabel?: string;
baseline?: unknown;
tenantId?: string | null;
children: ReactNode;
}
@@ -33,6 +34,7 @@ export function FormProvider({
hideEnterprise = false,
recordLabel = '',
baseline = null,
tenantId = null,
children,
}: FormProviderProps) {
const isCommunity = useIsCommunity();
@@ -46,6 +48,7 @@ export function FormProvider({
idPrefix,
recordLabel,
baseline,
tenantId,
};
const scope: FieldScope = { path: [], readOnly };
return (
+1
View File
@@ -18,6 +18,7 @@ export interface FormContextValue {
idPrefix: string;
recordLabel: string;
baseline: unknown;
tenantId: string | null;
}
export interface FieldScope {
+2 -2
View File
@@ -235,8 +235,8 @@ function MapKeyObjectIdInput({
onChange: (v: string) => void;
existingKeys: Record<string, unknown>;
}) {
const { schema } = useFormContext();
const list = useObjectOptions(objectName, schema);
const { schema, tenantId } = useFormContext();
const list = useObjectOptions(objectName, schema, tenantId);
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
return (
<div className="flex flex-1 items-center gap-2">
@@ -47,9 +47,9 @@ export function ObjectIdWidget({
control,
}: WidgetProps<FieldTypeObjectId>) {
const { t } = useTranslation();
const { schema } = useFormContext();
const { schema, tenantId } = useFormContext();
const id = typeof value === 'string' ? value : '';
const list = useObjectOptions(type.objectName, schema);
const list = useObjectOptions(type.objectName, schema, tenantId);
const noPermissionMessage = useNoPermissionMessage(schema, type.objectName);
return (
@@ -99,8 +99,8 @@ export function ObjectIdMultiSelect({
control,
}: ObjectIdMultiSelectProps) {
const { t } = useTranslation();
const { schema } = useFormContext();
const list = useObjectOptions(objectName, schema);
const { schema, tenantId } = useFormContext();
const list = useObjectOptions(objectName, schema, tenantId);
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
const available = list.options.filter((o) => !items.includes(o.id));
const atMinimum = minItems != null && items.length <= minItems;
+1 -2
View File
@@ -26,7 +26,7 @@ import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
import { DynamicIcon } from '@/components/common/DynamicIcon';
import { useUIStore } from '@/stores/uiStore';
import { useAuthStore } from '@/stores/authStore';
import { buildEndSessionUrl, getPostLogoutRedirectUri, revokeSessionTokens } from '@/services/auth/oauth';
import { buildEndSessionUrl, getPostLogoutRedirectUri } from '@/services/auth/oauth';
import { useEffect, useState } from 'react';
import { useIsCommunity } from '@/hooks/usePermissions';
import { SIDEBAR_ID } from './sidebarContext';
@@ -186,7 +186,6 @@ export function TopBar() {
const endSessionUrl = endSessionEndpoint
? buildEndSessionUrl(endSessionEndpoint, getPostLogoutRedirectUri())
: null;
if (endSessionUrl) revokeSessionTokens();
logout();
if (endSessionUrl) {
window.location.href = endSessionUrl;
+2 -1
View File
@@ -19,7 +19,8 @@ export const jmapKeys = {
lists: (objectName: string) => ['jmap', objectName, 'list'] as const,
list: (objectName: string, params: ListPageParams) => ['jmap', objectName, 'list', params] as const,
allOptions: (objectName: string) => ['jmap', objectName, 'options'] as const,
options: (objectName: string, viewName: string) => ['jmap', objectName, 'options', viewName] as const,
options: (objectName: string, viewName: string, tenantId: string | null = null) =>
['jmap', objectName, 'options', viewName, tenantId] as const,
displayNames: (objectName: string) => ['jmap', objectName, 'displayName'] as const,
displayName: (objectName: string, displayProperty: string, id: string) =>
['jmap', objectName, 'displayName', displayProperty, id] as const,
+13 -7
View File
@@ -9,7 +9,7 @@ import { queryOptions, useQuery, useQueryClient, type QueryClient } from '@tanst
import { jmapKeys } from '@/data/keys';
import { loadDisplayName } from '@/data/displayNames';
import { coerceLabel } from '@/lib/objectOptions';
import { getDisplayProperty, resolveList, resolveObject } from '@/lib/schemaResolver';
import { getDisplayProperty, isTenantScoped, resolveList, resolveObject, TENANT_PROPERTY } from '@/lib/schemaResolver';
import { jmapQueryAllAndGet } from '@/services/jmap/client';
import type { Schema } from '@/types/schema';
@@ -48,14 +48,20 @@ export function displayNameQuery(schema: Schema, viewOrObjectName: string, id: s
});
}
export function objectOptionsQuery(schema: Schema, viewOrObjectName: string) {
export function objectOptionsQuery(schema: Schema, viewOrObjectName: string, tenantId: string | null = null) {
const objectName = parentObjectName(schema, viewOrObjectName);
const displayProperty = getDisplayProperty(schema, viewOrObjectName);
const filtersStatic = resolveList(schema, viewOrObjectName, objectName)?.filtersStatic;
const filter = filtersStatic && Object.keys(filtersStatic).length > 0 ? filtersStatic : undefined;
const scopedTenantId = tenantId !== null && isTenantScoped(schema, viewOrObjectName) ? tenantId : null;
return queryOptions({
queryKey: jmapKeys.options(objectName, viewOrObjectName),
queryKey: jmapKeys.options(objectName, viewOrObjectName, scopedTenantId),
queryFn: async ({ signal }): Promise<ObjectOption[]> => {
const filtersStatic = resolveList(schema, viewOrObjectName, objectName)?.filtersStatic;
const filter =
scopedTenantId !== null
? { ...filtersStatic, [TENANT_PROPERTY]: scopedTenantId }
: filtersStatic && Object.keys(filtersStatic).length > 0
? filtersStatic
: undefined;
const { list } = await jmapQueryAllAndGet(objectName, { filter }, ['id', displayProperty], { signal });
const options: ObjectOption[] = [];
for (const item of list) {
@@ -69,10 +75,10 @@ export function objectOptionsQuery(schema: Schema, viewOrObjectName: string) {
const EMPTY_OPTIONS: ObjectOption[] = [];
export function useObjectOptions(viewOrObjectName: string, schema: Schema) {
export function useObjectOptions(viewOrObjectName: string, schema: Schema, tenantId: string | null = null) {
const [requested, setRequested] = useState(false);
const query = useQuery({
...objectOptionsQuery(schema, viewOrObjectName),
...objectOptionsQuery(schema, viewOrObjectName, tenantId),
enabled: requested,
});
const { isError, refetch } = query;
-61
View File
@@ -1,61 +0,0 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { describe, expect, it } from 'vitest';
import type { Schema } from '@/types/schema';
import { isLinkVisible } from '@/lib/layout';
import { createPermissionCheckers, isCreateOnly } from '@/lib/permissions';
const permission = (name: string) => ({ name, label: name });
const schema = {
objects: {
'x:Action': { type: 'object', description: '', permissionPrefix: 'sysAction' },
'x:Domain': { type: 'object', description: '', permissionPrefix: 'sysDomain' },
'x:Legacy': { type: 'object', description: '', permissionPrefix: 'sysLegacy' },
'x:DomainView': { type: 'view', objectName: 'x:Domain' },
},
schemas: {},
fields: {},
forms: {},
lists: {},
enums: {
Permission: ['sysActionCreate', 'sysDomainGet', 'sysDomainCreate'].map(permission),
},
dashboards: [],
layouts: [],
} as unknown as Schema;
function visible(viewName: string, granted: string[]): boolean {
const { canGet, hasPermission } = createPermissionCheckers(granted);
return isLinkVisible(schema, viewName, canGet, hasPermission);
}
describe('isCreateOnly', () => {
it('detects objects whose only defined permission is Create', () => {
expect(isCreateOnly(schema, 'sysAction')).toBe(true);
expect(isCreateOnly(schema, 'sysDomain')).toBe(false);
expect(isCreateOnly(schema, 'sysLegacy')).toBe(false);
});
});
describe('isLinkVisible', () => {
it('shows create-only objects to users holding the Create permission', () => {
expect(visible('x:Action', ['sysActionCreate'])).toBe(true);
expect(visible('x:Action', [])).toBe(false);
});
it('requires Get for objects that define it', () => {
expect(visible('x:Domain', ['sysDomainGet'])).toBe(true);
expect(visible('x:DomainView', ['sysDomainGet'])).toBe(true);
expect(visible('x:Domain', ['sysDomainCreate'])).toBe(false);
});
it('falls back to Get for objects missing from the permission enum', () => {
expect(visible('x:Legacy', ['sysLegacyGet'])).toBe(true);
expect(visible('x:Legacy', ['sysLegacyCreate'])).toBe(false);
});
});
+17
View File
@@ -78,6 +78,23 @@ export function resolveSchema(schema: Schema, objectName: string): ResolvedSchem
};
}
export const TENANT_PROPERTY = 'memberTenantId';
function hasTenantProperty(schema: Schema, schemaName: string | undefined): boolean {
if (schemaName === undefined) return false;
const fields = schema.fields[schemaName];
return fields !== undefined && Object.hasOwn(fields.properties, TENANT_PROPERTY);
}
export function isTenantScoped(schema: Schema, viewOrObjectName: string): boolean {
const entry = schema.objects[viewOrObjectName];
const objectName = entry?.type === 'view' ? entry.objectName : viewOrObjectName;
const schemaEntry = schema.schemas[objectName];
if (!schemaEntry) return false;
if (schemaEntry.type === 'single') return hasTenantProperty(schema, schemaEntry.schemaName);
return schemaEntry.variants.some((v) => hasTenantProperty(schema, v.schemaName));
}
export function resolveList(schema: Schema, viewName: string, objectName: string): List | null {
return schema.lists[viewName] ?? schema.lists[objectName] ?? null;
}
+10 -3
View File
@@ -52,7 +52,7 @@ export default function OAuthCallback() {
throw new Error(t('oauth.missingParams', 'Missing authorization code or state parameter'));
}
const { codeVerifier, tokenEndpoint, state, returnUrl, endSessionEndpoint, clientId, revocationEndpoint } =
const { codeVerifier, tokenEndpoint, state, returnUrl, endSessionEndpoint, clientId, resource } =
getStoredOAuthData();
if (!state || state !== stateParam) {
@@ -64,7 +64,14 @@ export default function OAuthCallback() {
}
const redirectUri = getOAuthRedirectUri();
const tokenResponse = await exchangeCodeOnce(code, codeVerifier, tokenEndpoint, redirectUri, clientId);
const tokenResponse = await exchangeCodeOnce(
code,
codeVerifier,
tokenEndpoint,
redirectUri,
clientId,
resource,
);
if (cancelled) return;
useAuthStore
@@ -76,7 +83,7 @@ export default function OAuthCallback() {
tokenEndpoint,
endSessionEndpoint,
clientId,
revocationEndpoint,
resource,
);
clearStoredOAuthData();
+11 -6
View File
@@ -25,21 +25,26 @@ function expireSession(): ApiError {
}
async function performRefresh(): Promise<void> {
const { refreshToken, tokenEndpoint, clientId } = useAuthStore.getState();
const { refreshToken, tokenEndpoint, clientId, resource } = useAuthStore.getState();
if (!refreshToken || !tokenEndpoint || !clientId) {
throw expireSession();
}
const body = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
});
if (resource) {
body.set('resource', resource);
}
let response: Response;
try {
response = await fetch(tokenEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
}),
body,
});
} catch (err) {
throw new NetworkError(err);
+34 -26
View File
@@ -18,10 +18,10 @@ export interface DiscoveryResponse {
authorization_endpoint: string;
token_endpoint: string;
end_session_endpoint?: string;
revocation_endpoint?: string;
scopes_supported?: string[];
client_id_metadata_document_supported?: boolean;
stalwart_required_scopes?: string[];
protected_resources?: string[];
}
export function selectScopes(
@@ -37,6 +37,23 @@ export function selectScopes(
return discovery.scopes_supported?.includes('openid') ? 'openid' : '';
}
export function selectResource(
apiBaseUrl: string,
discovery: Pick<DiscoveryResponse, 'protected_resources'>,
): string | null {
let origin: string;
try {
const url = new URL(apiBaseUrl);
if (url.protocol !== 'https:') return null;
origin = url.origin;
} catch {
return null;
}
const listed = discovery.protected_resources;
if (Array.isArray(listed) && !listed.includes(origin)) return null;
return origin;
}
export async function discover(username: string): Promise<DiscoveryResponse> {
const url = `${getApiBaseUrl()}/api/discover/${encodeURIComponent(username)}`;
const response = await fetch(url);
@@ -110,6 +127,7 @@ export async function exchangeCode(
tokenEndpoint: string,
redirectUri: string,
clientId: string,
resource: string | null,
): Promise<TokenResponse> {
const body = new URLSearchParams({
grant_type: 'authorization_code',
@@ -118,6 +136,9 @@ export async function exchangeCode(
client_id: clientId,
redirect_uri: redirectUri,
});
if (resource) {
body.set('resource', resource);
}
const response = await fetch(tokenEndpoint, {
method: 'POST',
@@ -144,7 +165,7 @@ function getRedirectUri(): string {
export async function startAuthFlow(username: string, returnUrl?: string | null): Promise<void> {
const discovery = await discover(username);
const { authorization_endpoint, token_endpoint, end_session_endpoint, revocation_endpoint } = discovery;
const { authorization_endpoint, token_endpoint, end_session_endpoint } = discovery;
const clientId = resolveOAuthClientId(discovery.client_id_metadata_document_supported === true);
if (!clientId) {
@@ -175,16 +196,17 @@ export async function startAuthFlow(username: string, returnUrl?: string | null)
sessionStorage.setItem(`${SESSION_PREFIX}state`, state);
sessionStorage.setItem(`${SESSION_PREFIX}return_url`, safeReturnUrl);
sessionStorage.setItem(`${SESSION_PREFIX}client_id`, clientId);
const resource = selectResource(getApiBaseUrl(), discovery);
if (resource) {
sessionStorage.setItem(`${SESSION_PREFIX}resource`, resource);
} else {
sessionStorage.removeItem(`${SESSION_PREFIX}resource`);
}
if (end_session_endpoint) {
sessionStorage.setItem(`${SESSION_PREFIX}end_session_endpoint`, end_session_endpoint);
} else {
sessionStorage.removeItem(`${SESSION_PREFIX}end_session_endpoint`);
}
if (revocation_endpoint) {
sessionStorage.setItem(`${SESSION_PREFIX}revocation_endpoint`, revocation_endpoint);
} else {
sessionStorage.removeItem(`${SESSION_PREFIX}revocation_endpoint`);
}
const params = new URLSearchParams({
response_type: 'code',
@@ -201,6 +223,9 @@ export async function startAuthFlow(username: string, returnUrl?: string | null)
if (scope) {
params.set('scope', scope);
}
if (resource) {
params.set('resource', resource);
}
window.location.href = `${authorization_endpoint}?${params.toString()}`;
}
@@ -212,8 +237,8 @@ export function getStoredOAuthData() {
state: sessionStorage.getItem(`${SESSION_PREFIX}state`),
returnUrl: sessionStorage.getItem(`${SESSION_PREFIX}return_url`),
endSessionEndpoint: sessionStorage.getItem(`${SESSION_PREFIX}end_session_endpoint`),
revocationEndpoint: sessionStorage.getItem(`${SESSION_PREFIX}revocation_endpoint`),
clientId: sessionStorage.getItem(`${SESSION_PREFIX}client_id`),
resource: sessionStorage.getItem(`${SESSION_PREFIX}resource`),
};
}
@@ -223,8 +248,8 @@ export function clearStoredOAuthData(): void {
sessionStorage.removeItem(`${SESSION_PREFIX}state`);
sessionStorage.removeItem(`${SESSION_PREFIX}return_url`);
sessionStorage.removeItem(`${SESSION_PREFIX}end_session_endpoint`);
sessionStorage.removeItem(`${SESSION_PREFIX}revocation_endpoint`);
sessionStorage.removeItem(`${SESSION_PREFIX}client_id`);
sessionStorage.removeItem(`${SESSION_PREFIX}resource`);
}
export function getOAuthRedirectUri(): string {
@@ -246,20 +271,3 @@ export function buildEndSessionUrl(endSessionEndpoint: string, postLogoutRedirec
const sep = endSessionEndpoint.includes('?') ? '&' : '?';
return `${endSessionEndpoint}${sep}${params.toString()}`;
}
export function revokeSessionTokens(): void {
const { revocationEndpoint, clientId, refreshToken, accessToken } = useAuthStore.getState();
const token = refreshToken || accessToken;
if (!revocationEndpoint || !clientId || !token) return;
const body = new URLSearchParams({
token,
token_type_hint: refreshToken ? 'refresh_token' : 'access_token',
client_id: clientId,
});
fetch(revocationEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
keepalive: true,
}).catch(() => undefined);
}
+7 -7
View File
@@ -19,8 +19,8 @@ interface AuthState {
tokenLifetime: number | null;
tokenEndpoint: string | null;
endSessionEndpoint: string | null;
revocationEndpoint: string | null;
clientId: string | null;
resource: string | null;
accounts: Record<string, AccountInfo>;
primaryAccountId: string | null;
activeAccountId: string | null;
@@ -36,7 +36,7 @@ interface AuthState {
tokenEndpoint: string,
endSessionEndpoint?: string | null,
clientId?: string | null,
revocationEndpoint?: string | null,
resource?: string | null,
) => void;
setSession: (
accounts: Record<string, AccountInfo>,
@@ -63,8 +63,8 @@ export const useAuthStore = create<AuthState>()(
tokenLifetime: null,
tokenEndpoint: null,
endSessionEndpoint: null,
revocationEndpoint: null,
clientId: null,
resource: null,
accounts: {},
primaryAccountId: null,
activeAccountId: null,
@@ -73,7 +73,7 @@ export const useAuthStore = create<AuthState>()(
maxObjectsInSet: 500,
sessionExpired: false,
setTokens: (access, refresh, expiresIn, tokenEndpoint, endSessionEndpoint, clientId, revocationEndpoint) => {
setTokens: (access, refresh, expiresIn, tokenEndpoint, endSessionEndpoint, clientId, resource) => {
const lifetime = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn * 1000 : null;
set({
accessToken: access,
@@ -83,7 +83,7 @@ export const useAuthStore = create<AuthState>()(
tokenEndpoint,
endSessionEndpoint: endSessionEndpoint === undefined ? get().endSessionEndpoint : endSessionEndpoint,
clientId: clientId === undefined ? get().clientId : clientId,
revocationEndpoint: revocationEndpoint === undefined ? get().revocationEndpoint : revocationEndpoint,
resource: resource === undefined ? get().resource : resource,
sessionExpired: false,
});
},
@@ -115,8 +115,8 @@ export const useAuthStore = create<AuthState>()(
tokenLifetime: null,
tokenEndpoint: null,
endSessionEndpoint: null,
revocationEndpoint: null,
clientId: null,
resource: null,
accounts: {},
primaryAccountId: null,
activeAccountId: null,
@@ -167,8 +167,8 @@ export const useAuthStore = create<AuthState>()(
tokenLifetime: state.tokenLifetime,
tokenEndpoint: state.tokenEndpoint,
endSessionEndpoint: state.endSessionEndpoint,
revocationEndpoint: state.revocationEndpoint,
clientId: state.clientId,
resource: state.resource,
activeAccountId: state.activeAccountId,
}) as AuthState,
},