diff --git a/.screenshots/groups-list.png b/.screenshots/groups-list.png
new file mode 100644
index 000000000..3c43f0747
Binary files /dev/null and b/.screenshots/groups-list.png differ
diff --git a/.screenshots/manage-home.png b/.screenshots/manage-home.png
new file mode 100644
index 000000000..3e754c5d1
Binary files /dev/null and b/.screenshots/manage-home.png differ
diff --git a/.screenshots/matrix-initial.png b/.screenshots/matrix-initial.png
new file mode 100644
index 000000000..d78ca7e8d
Binary files /dev/null and b/.screenshots/matrix-initial.png differ
diff --git a/apps/docs/docs/management/apps/index.mdx b/apps/docs/docs/management/apps/index.mdx
index a2fde8e48..49d6e504c 100644
--- a/apps/docs/docs/management/apps/index.mdx
+++ b/apps/docs/docs/management/apps/index.mdx
@@ -53,4 +53,4 @@ Note that the ping URL only accepts `http://` and `https://` URLs — custom URI
On the apps management page you find all apps that exist in your Homarr instance. Search by name or URL, open an app directly, or use its row actions to edit and delete it. A filtered search can be cleared without leaving the page.
-Any signed-in user can view this list. Creating, editing, and deleting apps requires the corresponding app permission; board permissions are not required.
+Viewing this list requires the `app-modify-all` permission. Creating an app requires `app-create`, editing requires `app-modify-all`, and deleting requires `app-full-all`; board permissions are not required.
diff --git a/apps/docs/docs/management/integrations/index.mdx b/apps/docs/docs/management/integrations/index.mdx
index a7ccbe1a6..1abcf6814 100644
--- a/apps/docs/docs/management/integrations/index.mdx
+++ b/apps/docs/docs/management/integrations/index.mdx
@@ -17,6 +17,8 @@ To create an integration, choose **New integration** and select the supported ap
The integrations management page uses a searchable list. Each row shows the integration type and URL, with the actions you have permission to use.
+This page is only visible to users with the global `integration-full-all` permission or with full access on at least one integration. Without the global permission, only the integrations you have full access to are shown.
+
Next, you'll need to fill out the required fields to configure the integration:

diff --git a/apps/docs/docs/management/users/index.mdx b/apps/docs/docs/management/users/index.mdx
index dd14f4a6d..4908cb231 100644
--- a/apps/docs/docs/management/users/index.mdx
+++ b/apps/docs/docs/management/users/index.mdx
@@ -163,19 +163,59 @@ Members can be removed from the group using the remove button at the end:
#### Permissions tab
In this tab, you manage what permissions the members of this group will have.
-Currently, the following permissions are available:
+Permissions are organized by category (boards, apps, integrations, and so on). Each category is a row with a
+segmented control that lets you pick a single access level. Selecting a level grants that level and every lower
+level in the same category. Choosing **None** removes all permissions for that category.
-- Boards
- - **Create boards**: Allow members to create boards
+Selecting **Administrator** grants full access to everything. While the administrator level is selected, every
+other category is disabled and shows a **Granted via Administrator** caption, because administrators already have
+all permissions. Deselecting it (choosing **None** on the administrator row) re-enables the other categories.
+
+##### Presets
+
+Above the rows you can apply a preset to fill in a common configuration in one click:
+
+- **Viewer**: view access to boards, use access to apps and integrations, and viewing media.
+- **Editor**: modify access to boards and apps, interact with integrations, modify search engines (includes creating), and viewing media.
+- **Admin**: grants the administrator permission (full access to everything).
+
+When the current selection does not match any preset, a **Custom** badge is shown.
+
+##### Implied permissions
+
+Some levels include additional permissions automatically. When a level implies extra permissions (for example,
+full board access also allows creating boards), a dimmed `also grants: …` hint is shown under the category row.
+
+##### Effective permissions
+
+Below the rows, the **Effective permissions** panel can be expanded to review everything members of this group
+will be able to do, including implied permissions, grouped by category with a count for each.
+
+Each category below is a segmented control that starts with **None**; the remaining segments are the access levels
+in ascending order (higher levels include the lower ones and may imply extra permissions shown in the hint):
+
+- Boards — None
- **View all boards**: Allow members to view all boards
- **Modify all boards**: Allow members to modify all boards (Does not include access control and danger zone)
- - **Full board access**: Allow members to view, modify, and delete all boards (Including access control and danger zone)
-- Integrations
- - **Create integrations**: Allow members to create integrations
- - **Use all integrations**: Allows members to add any integrations to their boards
+ - **Full board access**: Allow members to view, modify, and delete all boards (Including access control and danger zone; includes creating boards)
+- Apps — None
+ - **Use all apps**: Allow members to add any apps to their boards
+ - **Modify all apps**: Allow members to modify all apps (includes creating apps)
+ - **Full app access**: Allow members to manage, use and delete any app
+- Integrations — None
+ - **Use all integrations**: Allow members to add any integrations to their boards
- **Interact with any integration**: Allow members to interact with any integration
- - **Full integration access**: Allow members to manage, use and interact with any integration
-- **Administrator**: Members with this permission have full access to all features and settings
+ - **Full integration access**: Allow members to manage, use and interact with any integration (includes creating integrations)
+- Search engines — None
+ - **Modify all search engines**: Allow members to modify all search engines (includes creating search engines)
+ - **Full search engine access**: Allow members to manage and delete any search engine
+- Medias — None
+ - **View all medias**: Allow members to view all medias
+ - **Full media access**: Allow members to manage and delete any media (includes uploading medias)
+- Other — None
+ - **View logs**: Allow members to view logs
+- Administrator — None
+ - **Administrator**: Members with this permission have full access to all features and settings
Custom Widget authoring, import, migration, preview, secrets, Workshop access, and placement configuration are reserved
for administrators and are not separate assignable group permissions. Board modifiers can still move, resize, change
diff --git a/apps/nextjs/src/app/[locale]/manage/apps/page.tsx b/apps/nextjs/src/app/[locale]/manage/apps/page.tsx
index f37c730cd..536bd6ca8 100644
--- a/apps/nextjs/src/app/[locale]/manage/apps/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/apps/page.tsx
@@ -1,5 +1,5 @@
import { Fragment } from "react";
-import { redirect } from "next/navigation";
+import { notFound, redirect } from "next/navigation";
import { ActionIcon, ActionIconGroup, Anchor, Avatar, Text } from "@mantine/core";
import { IconBox, IconPencil } from "@tabler/icons-react";
import { z } from "zod/v4";
@@ -41,12 +41,12 @@ interface AppsPageProps {
export default async function AppsPage(props: AppsPageProps) {
const session = await auth();
if (!session) redirect("/auth/login");
+ if (!session.user.permissions.includes("app-modify-all")) notFound();
const searchParams = searchParamsSchema.parse(await props.searchParams);
const { items: apps, totalCount } = await api.app.getPaginated(searchParams);
const t = await getScopedI18n("app");
const canCreate = session.user.permissions.includes("app-create");
- const canModify = session.user.permissions.includes("app-modify-all");
const canDelete = session.user.permissions.includes("app-full-all");
const hasSearch = Boolean(searchParams.search?.trim());
@@ -100,7 +100,6 @@ export default async function AppsPage(props: AppsPageProps) {
@@ -113,12 +112,11 @@ export default async function AppsPage(props: AppsPageProps) {
interface AppItemProps {
app: RouterOutputs["app"]["getPaginated"]["items"][number];
- canModify: boolean;
canDelete: boolean;
editLabel: string;
}
-const AppItem = ({ app, canModify, canDelete, editLabel }: AppItemProps) => {
+const AppItem = ({ app, canDelete, editLabel }: AppItemProps) => {
const descriptionLines = app.description?.split("\n");
const safeHref = getSafeAppHref(app.href);
@@ -157,23 +155,19 @@ const AppItem = ({ app, canModify, canDelete, editLabel }: AppItemProps) => {
) : undefined
}
actions={
- canModify || canDelete ? (
-
- {canModify && (
-
-
-
- )}
- {canDelete && }
-
- ) : undefined
+
+
+
+
+ {canDelete && }
+
}
/>
);
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/page.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/page.tsx
index 785137023..6488b5f26 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/page.tsx
@@ -1,5 +1,5 @@
import { redirect } from "next/navigation";
-import { ActionIcon, ActionIconGroup, Anchor, Badge, Text } from "@mantine/core";
+import { ActionIcon, ActionIconGroup, Anchor, Badge, Stack, Text } from "@mantine/core";
import { IconPencil, IconPlugX } from "@tabler/icons-react";
import { z } from "zod/v4";
@@ -32,8 +32,11 @@ export default async function IntegrationsPage(props: IntegrationsPageProps) {
const t = await getScopedI18n("integration");
const canCreate = session.user.permissions.includes("integration-create");
const hasGlobalFullAccess = session.user.permissions.includes("integration-full-all");
+ const canSee = hasGlobalFullAccess || integrations.some((integration) => integration.permissions.hasFullAccess);
+
const query = searchParams.search?.trim().toLocaleLowerCase() ?? "";
const filteredIntegrations = integrations
+ .filter((integration) => hasGlobalFullAccess || integration.permissions.hasFullAccess)
.filter((integration) => {
if (!query) return true;
return [integration.name, getIntegrationName(integration.kind), integration.url].some((value) =>
@@ -53,7 +56,13 @@ export default async function IntegrationsPage(props: IntegrationsPageProps) {
ariaLabel={t("page.list.ariaLabel")}
itemCount={filteredIntegrations.length}
emptyState={
- hasSearch ? (
+ !canSee ? (
+
+ ) : hasSearch ? (
{filteredIntegrations.map((integration) => (
-
+
))}
);
- return filteredIntegrations.length > 0 ? {page} : page;
+ const pageContent =
+ filteredIntegrations.length > 0 ? {page} : page;
+
+ if (hasGlobalFullAccess) {
+ return pageContent;
+ }
+
+ return (
+
+
+ {t("page.list.scopedNote")}
+
+ {pageContent}
+
+ );
}
interface IntegrationItemProps {
integration: RouterOutputs["integration"]["all"][number];
- canManage: boolean;
}
-const IntegrationItem = async ({ integration, canManage }: IntegrationItemProps) => {
+const IntegrationItem = async ({ integration }: IntegrationItemProps) => {
const t = await getScopedI18n("integration");
const kindName = getIntegrationName(integration.kind);
const safeUrl = getSafeApplicationUrl(integration.url);
@@ -143,21 +161,19 @@ const IntegrationItem = async ({ integration, canManage }: IntegrationItemProps)
) : undefined
}
actions={
- canManage ? (
-
-
-
-
-
-
- ) : undefined
+
+
+
+
+
+
}
/>
);
diff --git a/apps/nextjs/src/app/[locale]/manage/layout.tsx b/apps/nextjs/src/app/[locale]/manage/layout.tsx
index 7fa486360..a011d67cd 100644
--- a/apps/nextjs/src/app/[locale]/manage/layout.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/layout.tsx
@@ -28,6 +28,7 @@ import {
IconUsersGroup,
} from "@tabler/icons-react";
+import { api } from "@homarr/api/server";
import { getRscUserSettingsAsync } from "@homarr/api/user-server";
import { auth } from "@homarr/auth/next";
import { isProviderEnabled } from "@homarr/auth/server";
@@ -65,6 +66,12 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
sessionPromise,
shouldRunManageTourPromise,
]);
+ const hasGlobalIntegrationFullAccess = session?.user.permissions.includes("integration-full-all") ?? false;
+ const hasDelegatedIntegrationFullAccess =
+ !hasGlobalIntegrationFullAccess && session
+ ? (await api.integration.all()).some((integration) => integration.permissions.hasFullAccess)
+ : false;
+ const canManageIntegrations = hasGlobalIntegrationFullAccess || hasDelegatedIntegrationFullAccess;
const navigationLinks: NavigationLink[] = [
{
label: t("items.home"),
@@ -82,7 +89,7 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
icon: IconBox,
href: "/manage/apps",
label: t("items.apps"),
- hidden: !session?.user.permissions.includes("app-create"),
+ hidden: !session?.user.permissions.includes("app-modify-all"),
iconProps: {
strokeWidth: 2.5,
},
@@ -92,7 +99,7 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
icon: IconAffiliateFilled,
href: "/manage/integrations",
label: t("items.integrations"),
- hidden: !session?.user.permissions.includes("integration-create"),
+ hidden: !canManageIntegrations,
"data-onboarding-tour-id": "manage-integrations",
},
{
diff --git a/apps/nextjs/src/app/[locale]/manage/not-found.tsx b/apps/nextjs/src/app/[locale]/manage/not-found.tsx
index f6931af9f..9b13fc3d7 100644
--- a/apps/nextjs/src/app/[locale]/manage/not-found.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/not-found.tsx
@@ -1,6 +1,7 @@
-import { Center, Stack, Text, Title } from "@mantine/core";
+import { Anchor, Center, Stack, Text, Title } from "@mantine/core";
import { getScopedI18n } from "@homarr/translation/server";
+import { Link } from "@homarr/ui";
export default async function NotFound() {
const t = await getScopedI18n("management.notFound");
@@ -9,6 +10,9 @@ export default async function NotFound() {
{t("title")}
{t("text")}
+
+ {t("backToHome")}
+
);
diff --git a/apps/nextjs/src/app/[locale]/manage/page.tsx b/apps/nextjs/src/app/[locale]/manage/page.tsx
index c7a3a1813..cb78663be 100644
--- a/apps/nextjs/src/app/[locale]/manage/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/page.tsx
@@ -29,7 +29,12 @@ export default async function ManagementPage() {
{statistics.map((statistic) => (
-
+
@@ -42,7 +47,7 @@ export default async function ManagementPage() {
{t(`statistic.${statistic.titleKey}`)}
-
+
))}
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/_group-permission-form.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/_group-permission-form.tsx
index 1ae1b119c..e91ec1d02 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/_group-permission-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/_group-permission-form.tsx
@@ -2,16 +2,37 @@
import type { PropsWithChildren } from "react";
import { useCallback } from "react";
-import { Button, Card, Group, Switch, Text, Transition } from "@mantine/core";
+import {
+ Badge,
+ Button,
+ Card,
+ Collapse,
+ Group,
+ SegmentedControl,
+ Stack,
+ Text,
+ Transition,
+ UnstyledButton,
+} from "@mantine/core";
+import { useDisclosure } from "@mantine/hooks";
+import { IconShieldExclamation } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
-import { objectEntries } from "@homarr/common";
-import type { GroupPermissionKey } from "@homarr/definitions";
-import { groupPermissionKeys } from "@homarr/definitions";
+import { objectEntries, objectKeys } from "@homarr/common";
+import type { GroupPermissionKey, PermissionMatrixCategory, PermissionMatrixState } from "@homarr/definitions";
+import {
+ getPermissionsWithChildren,
+ groupPermissionKeys,
+ matrixStateToPermissions,
+ permissionMatrix,
+ permissionsToMatrixState,
+} from "@homarr/definitions";
import { createFormContext } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
+export type PermissionLabels = Partial>;
+
const [FormProvider, useFormContext, useForm] = createFormContext();
interface PermissionFormProps {
@@ -39,7 +60,7 @@ export const PermissionForm = ({ children, initialPermissions }: PropsWithChildr
});
return (
-
);
@@ -47,15 +68,222 @@ export const PermissionForm = ({ children, initialPermissions }: PropsWithChildr
type FormType = Record;
-export const PermissionSwitch = ({ name }: { name: GroupPermissionKey }) => {
- const form = useFormContext();
+type MatrixForm = ReturnType;
- const props = form.getInputProps(name, {
- withError: false,
- type: "checkbox",
+const emptyMatrixState = (): PermissionMatrixState =>
+ objectKeys(permissionMatrix).reduce((acc, category) => {
+ acc[category] = { level: 0 };
+ return acc;
+ }, {} as PermissionMatrixState);
+
+export const getMatrixLevel = (values: FormType, category: PermissionMatrixCategory): number => {
+ const checkedKeys = groupPermissionKeys.filter((key) => values[key]);
+ return permissionsToMatrixState(checkedKeys)[category].level;
+};
+
+export const applyMatrixLevel = (form: MatrixForm, category: PermissionMatrixCategory, level: number) => {
+ const targetKeys = new Set(matrixStateToPermissions({ ...emptyMatrixState(), [category]: { level } }));
+ permissionMatrix[category].levels.forEach((key) => {
+ form.setFieldValue(key, targetKeys.has(key));
});
+};
- return ;
+const presets = {
+ viewer: { board: 1, app: 1, integration: 1, media: 1 },
+ editor: { board: 2, app: 2, integration: 2, "search-engine": 1, media: 1 },
+ admin: { admin: 1 },
+} satisfies Record>>;
+
+export type PermissionPreset = keyof typeof presets;
+
+const presetToFormState = (preset: PermissionPreset): FormType => {
+ const levels: Partial> = presets[preset];
+ const state = objectKeys(permissionMatrix).reduce((acc, category) => {
+ acc[category] = { level: levels[category] ?? 0 };
+ return acc;
+ }, {} as PermissionMatrixState);
+ const enabledKeys = new Set(matrixStateToPermissions(state));
+
+ return groupPermissionKeys.reduce((acc, key) => {
+ acc[key] = enabledKeys.has(key);
+ return acc;
+ }, {} as FormType);
+};
+
+export const applyPreset = (form: MatrixForm, preset: PermissionPreset) => {
+ form.setValues(presetToFormState(preset));
+};
+
+export const getActivePreset = (values: FormType): PermissionPreset | null => {
+ return (
+ objectKeys(presets).find((preset) => {
+ const presetValues = presetToFormState(preset);
+ return groupPermissionKeys.every((key) => presetValues[key] === values[key]);
+ }) ?? null
+ );
+};
+
+interface MatrixImpliedHintProps {
+ category: PermissionMatrixCategory;
+ permissionLabels: PermissionLabels;
+}
+
+export const MatrixImpliedHint = ({ category, permissionLabels }: MatrixImpliedHintProps) => {
+ const form = useFormContext();
+ const tPermissions = useScopedI18n("group.permission");
+
+ const level = getMatrixLevel(form.getValues(), category);
+ if (level === 0) {
+ return null;
+ }
+
+ const checkedKeys: GroupPermissionKey[] = permissionMatrix[category].levels.slice(0, level);
+ const implied = getPermissionsWithChildren(checkedKeys).filter((key) => !checkedKeys.includes(key));
+ if (implied.length === 0) {
+ return null;
+ }
+
+ const labels = implied.map((key) => permissionLabels[key] ?? key);
+
+ return (
+
+ {tPermissions("matrix.impliedHint", { permissions: labels.join(", ") })}
+
+ );
+};
+
+interface MatrixRowProps {
+ category: PermissionMatrixCategory;
+ permissionLabels: PermissionLabels;
+}
+
+export const MatrixRow = ({ category, permissionLabels }: MatrixRowProps) => {
+ const form = useFormContext();
+ const tPermissions = useScopedI18n("group.permission");
+
+ const values = form.getValues();
+ const level = getMatrixLevel(values, category);
+ const isDanger = category === "admin";
+ const disabledByAdmin = !isDanger && getMatrixLevel(values, "admin") > 0;
+
+ const data = [
+ { value: "0", label: tPermissions("matrix.none") },
+ ...permissionMatrix[category].levels.map((key, index) => ({
+ value: String(index + 1),
+ label: permissionLabels[key] ?? key,
+ })),
+ ];
+
+ return (
+
+
+
+ {isDanger && }
+
+ {tPermissions(`${category}.title`)}
+
+
+ applyMatrixLevel(form, category, Number(value))}
+ />
+ {disabledByAdmin && (
+
+ {tPermissions("matrix.grantedViaAdmin")}
+
+ )}
+
+
+
+ );
+};
+
+export const PresetButtons = () => {
+ const form = useFormContext();
+ const tPermissions = useScopedI18n("group.permission");
+ const activePreset = getActivePreset(form.getValues());
+
+ return (
+
+
+ {tPermissions("matrix.preset.label")}
+
+ {(["viewer", "editor", "admin"] as const).map((preset) => (
+
+ ))}
+ {activePreset === null && {tPermissions("matrix.preset.custom")}}
+
+ );
+};
+
+interface EffectivePermissionPreviewProps {
+ permissionLabels: PermissionLabels;
+}
+
+export const EffectivePermissionPreview = ({ permissionLabels }: EffectivePermissionPreviewProps) => {
+ const form = useFormContext();
+ const tPermissions = useScopedI18n("group.permission");
+ const [opened, { toggle }] = useDisclosure(false);
+
+ const values = form.getValues();
+ const checkedKeys = groupPermissionKeys.filter((key) => values[key]);
+ const effective = getPermissionsWithChildren(checkedKeys);
+
+ const grouped = objectKeys(permissionMatrix)
+ .map((category) => ({
+ category,
+ keys: effective.filter((key) => key === category || key.startsWith(`${category}-`)),
+ }))
+ .filter(({ keys }) => keys.length > 0);
+
+ return (
+
+
+
+
+ {tPermissions("matrix.effective.title")}
+
+ {tPermissions("matrix.effective.description")}
+
+
+ {effective.length}
+
+
+
+
+ {grouped.length === 0 ? (
+
+ {tPermissions("matrix.effective.empty")}
+
+ ) : (
+ grouped.map(({ category, keys }) => (
+
+
+ {tPermissions(`${category}.title`)}
+
+
+ {keys.length}
+
+
+ {keys.map((key) => permissionLabels[key] ?? key).join(", ")}
+
+
+ ))
+ )}
+
+
+
+ );
};
interface SaveAffixProps {
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/page.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/page.tsx
index 0ba8ae9d1..39e1b10d4 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/page.tsx
@@ -1,15 +1,21 @@
-import React from "react";
import { notFound } from "next/navigation";
-import { Card, CardSection, Divider, Group, Stack, Text, Title } from "@mantine/core";
+import { Stack, Title } from "@mantine/core";
import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
import { objectKeys } from "@homarr/common";
import type { GroupPermissionKey } from "@homarr/definitions";
-import { groupPermissions } from "@homarr/definitions";
+import { groupPermissions, permissionMatrix } from "@homarr/definitions";
import { getI18n, getScopedI18n } from "@homarr/translation/server";
-import { PermissionForm, PermissionSwitch, SaveAffix } from "./_group-permission-form";
+import type { PermissionLabels } from "./_group-permission-form";
+import {
+ EffectivePermissionPreview,
+ MatrixRow,
+ PermissionForm,
+ PresetButtons,
+ SaveAffix,
+} from "./_group-permission-form";
interface GroupPermissionsPageProps {
params: Promise<{
@@ -26,27 +32,25 @@ export default async function GroupPermissionsPage(props: GroupPermissionsPagePr
}
const group = await api.group.getById({ id: params.id });
- const tPermissions = await getScopedI18n("group.permission");
const t = await getI18n();
+ const permissionLabels = await buildPermissionLabels();
+
return (
{t("management.page.group.setting.permissions.title")}
- {objectKeys(groupPermissions).map((group) => {
- const isDanger = group === "admin";
+
- return (
-
-
- {tPermissions(`${group}.title`)}
-
-
-
- );
- })}
+
+ {objectKeys(permissionMatrix).map((category) => (
+
+ ))}
+
+
+
@@ -55,66 +59,19 @@ export default async function GroupPermissionsPage(props: GroupPermissionsPagePr
);
}
-interface PermissionCardProps {
- group: keyof typeof groupPermissions;
- isDanger: boolean;
-}
+const buildPermissionLabels = async (): Promise => {
+ const permissionLabels: PermissionLabels = {};
-const PermissionCard = async ({ group, isDanger }: PermissionCardProps) => {
- const t = await getScopedI18n(`group.permission.${group}.item`);
- const item = groupPermissions[group];
- const permissions = typeof item !== "boolean" ? item : ([group] as "admin"[]);
+ for (const category of objectKeys(groupPermissions)) {
+ const tItem = await getScopedI18n(`group.permission.${category}.item`);
+ const item = groupPermissions[category];
+ const suffixes = typeof item !== "boolean" ? item : (["admin"] as const);
- return (
-
-
- {permissions.map((permission, index) => (
-
-
-
- {index < permissions.length - 1 && (
-
-
-
- )}
-
- ))}
-
-
- );
-};
-
-const createGroupPermissionKey = (group: keyof typeof groupPermissions, permission: string): GroupPermissionKey => {
- if (typeof groupPermissions[group] === "boolean") {
- return group as GroupPermissionKey;
+ suffixes.forEach((suffix) => {
+ const key = (typeof item !== "boolean" ? `${category}-${suffix}` : "admin") as GroupPermissionKey;
+ permissionLabels[key] = tItem(`${suffix}.label`);
+ });
}
- return `${group}-${permission}` as GroupPermissionKey;
-};
-
-interface PermissionRowProps {
- name: GroupPermissionKey;
- label: string;
- description: string;
-}
-
-const PermissionRow = ({ name, label, description }: PermissionRowProps) => {
- return (
-
-
- {label}
- {description}
-
-
-
- );
+ return permissionLabels;
};
diff --git a/packages/api/src/router/app.ts b/packages/api/src/router/app.ts
index 3698d7f86..d0e4b4b18 100644
--- a/packages/api/src/router/app.ts
+++ b/packages/api/src/router/app.ts
@@ -18,7 +18,8 @@ import { AppAccessControl } from "./app/app-access-control";
const defaultIcon = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/homarr.svg";
export const appRouter = createTRPCRouter({
- getPaginated: protectedProcedure
+ getPaginated: permissionRequiredProcedure
+ .requiresPermission("app-modify-all")
.meta({
openapi: {
method: "GET",
@@ -50,7 +51,8 @@ export const appRouter = createTRPCRouter({
totalCount,
};
}),
- all: protectedProcedure
+ all: permissionRequiredProcedure
+ .requiresPermission("app-modify-all")
.input(z.void())
.output(z.array(selectAppSchema))
.meta({
@@ -67,7 +69,8 @@ export const appRouter = createTRPCRouter({
orderBy: asc(apps.name),
});
}),
- search: protectedProcedure
+ search: permissionRequiredProcedure
+ .requiresPermission("app-modify-all")
.input(
z.object({
query: z.string(),
diff --git a/packages/api/src/router/group.ts b/packages/api/src/router/group.ts
index 5e8f8834b..5396af94d 100644
--- a/packages/api/src/router/group.ts
+++ b/packages/api/src/router/group.ts
@@ -9,6 +9,7 @@ import type { Database } from "@homarr/db";
import { and, eq, handleTransactionsAsync, like, not } from "@homarr/db";
import { getMaxGroupPositionAsync } from "@homarr/db/queries";
import { groupMembers, groupPermissions, groups, onboarding, users } from "@homarr/db/schema";
+import type { GroupPermissionKey } from "@homarr/definitions";
import { everyoneGroup } from "@homarr/definitions";
import { byIdSchema, paginatedSchema } from "@homarr/validation/common";
import {
@@ -22,6 +23,13 @@ import {
import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, protectedProcedure } from "../trpc";
+const createPermissionParents = {
+ "app-create": "app-modify-all",
+ "integration-create": "integration-full-all",
+ "board-create": "board-modify-all",
+ "search-engine-create": "search-engine-modify-all",
+} satisfies Partial>;
+
export const groupRouter = createTRPCRouter({
getAll: permissionRequiredProcedure.requiresPermission("admin").query(async ({ ctx }) => {
const dbGroups = await ctx.db.query.groups.findMany({
@@ -302,16 +310,52 @@ export const groupRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
- await ctx.db.delete(groupPermissions).where(eq(groupPermissions.groupId, input.groupId));
+ const permissions = [
+ ...new Set(
+ input.permissions.flatMap((permission) => {
+ const parent = createPermissionParents[permission as keyof typeof createPermissionParents] as
+ | GroupPermissionKey
+ | undefined;
+ return parent ? [permission, parent] : [permission];
+ }),
+ ),
+ ];
- if (input.permissions.length > 0) {
- await ctx.db.insert(groupPermissions).values(
- input.permissions.map((permission) => ({
- groupId: input.groupId,
- permission,
- })),
- );
- }
+ await handleTransactionsAsync(ctx.db, {
+ async handleAsync(db, schema) {
+ await db.transaction(async (transaction) => {
+ await transaction
+ .delete(schema.groupPermissions)
+ .where(eq(schema.groupPermissions.groupId, input.groupId));
+ if (permissions.length === 0) {
+ return;
+ }
+ await transaction.insert(schema.groupPermissions).values(
+ permissions.map((permission) => ({
+ groupId: input.groupId,
+ permission,
+ })),
+ );
+ });
+ },
+ handleSync(db) {
+ db.transaction((transaction) => {
+ transaction.delete(groupPermissions).where(eq(groupPermissions.groupId, input.groupId)).run();
+ if (permissions.length === 0) {
+ return;
+ }
+ transaction
+ .insert(groupPermissions)
+ .values(
+ permissions.map((permission) => ({
+ groupId: input.groupId,
+ permission,
+ })),
+ )
+ .run();
+ });
+ },
+ });
}),
transferOwnership: permissionRequiredProcedure
.requiresPermission("admin")
diff --git a/packages/api/src/router/home.ts b/packages/api/src/router/home.ts
index f33cea48f..c7ed9c138 100644
--- a/packages/api/src/router/home.ts
+++ b/packages/api/src/router/home.ts
@@ -1,4 +1,6 @@
import { isProviderEnabled } from "@homarr/auth/server";
+import { constructIntegrationPermissions } from "@homarr/auth/shared";
+import type { Database } from "@homarr/db";
import { db, eq, inArray, or } from "@homarr/db";
import {
apps,
@@ -6,6 +8,8 @@ import {
boardUserPermissions,
groupMembers,
groups,
+ integrationGroupPermissions,
+ integrationUserPermissions,
integrations,
invites,
medias,
@@ -16,6 +20,33 @@ import type { TranslationObject } from "@homarr/translation";
import { createTRPCRouter, publicProcedure } from "../trpc";
+const getFullAccessIntegrationIdsAsync = async (db: Database, userId: string) => {
+ const groupsOfCurrentUser = await db.query.groupMembers.findMany({
+ where: eq(groupMembers.userId, userId),
+ });
+
+ const accessibleIntegrations = await db.query.integrations.findMany({
+ columns: {
+ id: true,
+ },
+ with: {
+ userPermissions: {
+ where: eq(integrationUserPermissions.userId, userId),
+ },
+ groupPermissions: {
+ where: inArray(
+ integrationGroupPermissions.groupId,
+ groupsOfCurrentUser.map((group) => group.groupId),
+ ),
+ },
+ },
+ });
+
+ return accessibleIntegrations
+ .filter((integration) => constructIntegrationPermissions(integration, null).hasFullAccess)
+ .map((integration) => integration.id);
+};
+
interface HomeStatistic {
titleKey: keyof TranslationObject["management"]["page"]["home"]["statistic"];
subtitleKey: keyof TranslationObject["management"]["page"]["home"]["statisticLabel"];
@@ -92,16 +123,20 @@ export const homeRouter = createTRPCRouter({
});
}
- if (ctx.session?.user.permissions.includes("integration-create")) {
+ const hasGlobalFullIntegrationAccess = ctx.session?.user.permissions.includes("integration-full-all") ?? false;
+ const fullAccessIntegrationIds = hasGlobalFullIntegrationAccess
+ ? []
+ : await getFullAccessIntegrationIdsAsync(ctx.db, ctx.session?.user.id ?? "");
+ if (hasGlobalFullIntegrationAccess || fullAccessIntegrationIds.length > 0) {
statistics.push({
titleKey: "integration",
subtitleKey: "resources",
- count: await db.$count(integrations),
+ count: hasGlobalFullIntegrationAccess ? await db.$count(integrations) : fullAccessIntegrationIds.length,
path: "/manage/integrations",
});
}
- if (ctx.session?.user.permissions.includes("app-create")) {
+ if (ctx.session?.user.permissions.includes("app-modify-all")) {
statistics.push({
titleKey: "app",
subtitleKey: "resources",
diff --git a/packages/api/src/router/integration/integration-router.ts b/packages/api/src/router/integration/integration-router.ts
index 552cd853f..d1235f9c8 100644
--- a/packages/api/src/router/integration/integration-router.ts
+++ b/packages/api/src/router/integration/integration-router.ts
@@ -1,12 +1,13 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
+import type { Session } from "@homarr/auth";
import { hasQueryAccessToIntegrationsAsync } from "@homarr/auth/server";
import { constructIntegrationPermissions } from "@homarr/auth/shared";
import { createId, objectEntries } from "@homarr/common";
import { decryptSecret, encryptSecret } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
-import type { Database } from "@homarr/db";
+import type { Database, SQL } from "@homarr/db";
import { and, asc, eq, handleTransactionsAsync, inArray, like, or } from "@homarr/db";
import {
apps,
@@ -17,7 +18,7 @@ import {
integrationSecrets,
integrationUserPermissions,
} from "@homarr/db/schema";
-import type { IntegrationSecretKind } from "@homarr/definitions";
+import type { GroupPermissionKey, IntegrationPermission, IntegrationSecretKind } from "@homarr/definitions";
import {
getIntegrationKindsByCategory,
getPermissionsWithParents,
@@ -71,80 +72,18 @@ export const integrationRouter = createTRPCRouter({
},
})
.query(async ({ ctx }) => {
- const groupsOfCurrentUser = await ctx.db.query.groupMembers.findMany({
- where: eq(groupMembers.userId, ctx.session.user.id),
- });
-
- const integrations = await ctx.db.query.integrations.findMany({
- with: {
- userPermissions: {
- where: eq(integrationUserPermissions.userId, ctx.session.user.id),
- },
- groupPermissions: {
- where: inArray(
- integrationGroupPermissions.groupId,
- groupsOfCurrentUser.map((group) => group.groupId),
- ),
- },
- },
- });
- return integrations
- .map((integration) => {
- const permissions = constructIntegrationPermissions(integration, ctx.session);
-
- return {
- id: integration.id,
- name: integration.name,
- kind: integration.kind,
- url: integration.url,
- permissions,
- };
- })
- .toSorted(
- (integrationA, integrationB) =>
- integrationKinds.indexOf(integrationA.kind) - integrationKinds.indexOf(integrationB.kind),
- );
+ return await getAccessibleIntegrationsAsync(ctx);
}),
allThatSupportSearch: protectedProcedure.query(async ({ ctx }) => {
- const groupsOfCurrentUser = await ctx.db.query.groupMembers.findMany({
- where: eq(groupMembers.userId, ctx.session.user.id),
- });
-
- const integrationsFromDb = await ctx.db.query.integrations.findMany({
- with: {
- userPermissions: {
- where: eq(integrationUserPermissions.userId, ctx.session.user.id),
- },
- groupPermissions: {
- where: inArray(
- integrationGroupPermissions.groupId,
- groupsOfCurrentUser.map((group) => group.groupId),
- ),
- },
- },
- where: inArray(
+ return await getAccessibleIntegrationsAsync(
+ ctx,
+ inArray(
integrations.kind,
objectEntries(integrationDefs)
.filter(([_, integration]) => [...integration.category].includes("search"))
.map(([kind, _]) => kind),
),
- });
- return integrationsFromDb
- .map((integration) => {
- const permissions = constructIntegrationPermissions(integration, ctx.session);
-
- return {
- id: integration.id,
- name: integration.name,
- kind: integration.kind,
- url: integration.url,
- permissions,
- };
- })
- .toSorted(
- (integrationA, integrationB) =>
- integrationKinds.indexOf(integrationA.kind) - integrationKinds.indexOf(integrationB.kind),
- );
+ );
}),
allOfGivenCategory: protectedProcedure
.input(
@@ -153,42 +92,10 @@ export const integrationRouter = createTRPCRouter({
}),
)
.query(async ({ ctx, input }) => {
- const groupsOfCurrentUser = await ctx.db.query.groupMembers.findMany({
- where: eq(groupMembers.userId, ctx.session.user.id),
- });
-
- const intergrationKinds = getIntegrationKindsByCategory(input.category);
-
- const integrationsFromDb = await ctx.db.query.integrations.findMany({
- with: {
- userPermissions: {
- where: eq(integrationUserPermissions.userId, ctx.session.user.id),
- },
- groupPermissions: {
- where: inArray(
- integrationGroupPermissions.groupId,
- groupsOfCurrentUser.map((group) => group.groupId),
- ),
- },
- },
- where: inArray(integrations.kind, intergrationKinds),
- });
- return integrationsFromDb
- .map((integration) => {
- const permissions = constructIntegrationPermissions(integration, ctx.session);
-
- return {
- id: integration.id,
- name: integration.name,
- kind: integration.kind,
- url: integration.url,
- permissions,
- };
- })
- .toSorted(
- (integrationA, integrationB) =>
- integrationKinds.indexOf(integrationA.kind) - integrationKinds.indexOf(integrationB.kind),
- );
+ return await getAccessibleIntegrationsAsync(
+ ctx,
+ inArray(integrations.kind, getIntegrationKindsByCategory(input.category)),
+ );
}),
search: protectedProcedure
.meta({
@@ -205,11 +112,32 @@ export const integrationRouter = createTRPCRouter({
}),
)
.query(async ({ ctx, input }) => {
- return await ctx.db.query.integrations.findMany({
+ const groupsOfCurrentUser = await ctx.db.query.groupMembers.findMany({
+ where: eq(groupMembers.userId, ctx.session.user.id),
+ });
+
+ const integrationsFromDb = await ctx.db.query.integrations.findMany({
where: like(integrations.name, `%${input.query}%`),
orderBy: asc(integrations.name),
- limit: input.limit,
+ with: {
+ userPermissions: {
+ where: eq(integrationUserPermissions.userId, ctx.session.user.id),
+ },
+ groupPermissions: {
+ where: inArray(
+ integrationGroupPermissions.groupId,
+ groupsOfCurrentUser.map((group) => group.groupId),
+ ),
+ },
+ },
});
+
+ return integrationsFromDb
+ .filter((integration) => hasIntegrationQueryAccess(ctx.session, integration))
+ .slice(0, input.limit)
+ .map(
+ ({ userPermissions: _userPermissions, groupPermissions: _groupPermissions, ...integration }) => integration,
+ );
}),
// This is used to get the integrations by their ids it's public because it's needed to get integrations data in the boards
byIds: publicProcedure.input(z.array(z.string())).query(async ({ ctx, input }) => {
@@ -774,6 +702,62 @@ export const integrationRouter = createTRPCRouter({
}),
});
+const globalIntegrationPermissions = [
+ "integration-use-all",
+ "integration-interact-all",
+ "integration-full-all",
+] satisfies GroupPermissionKey[];
+
+const hasGlobalIntegrationAccess = (session: Session | null) =>
+ globalIntegrationPermissions.some((permission) => session?.user.permissions.includes(permission) ?? false);
+
+const hasIntegrationQueryAccess = (
+ session: Session | null,
+ integration: {
+ userPermissions: { permission: IntegrationPermission }[];
+ groupPermissions: { permission: IntegrationPermission }[];
+ },
+) => hasGlobalIntegrationAccess(session) || constructIntegrationPermissions(integration, session).hasUseAccess;
+
+const getAccessibleIntegrationsAsync = async (ctx: { db: Database; session: Session }, where?: SQL) => {
+ const groupsOfCurrentUser = await ctx.db.query.groupMembers.findMany({
+ where: eq(groupMembers.userId, ctx.session.user.id),
+ });
+
+ const integrationsFromDb = await ctx.db.query.integrations.findMany({
+ where,
+ with: {
+ userPermissions: {
+ where: eq(integrationUserPermissions.userId, ctx.session.user.id),
+ },
+ groupPermissions: {
+ where: inArray(
+ integrationGroupPermissions.groupId,
+ groupsOfCurrentUser.map((group) => group.groupId),
+ ),
+ },
+ },
+ });
+
+ return integrationsFromDb
+ .filter((integration) => hasIntegrationQueryAccess(ctx.session, integration))
+ .map((integration) => {
+ const permissions = constructIntegrationPermissions(integration, ctx.session);
+
+ return {
+ id: integration.id,
+ name: integration.name,
+ kind: integration.kind,
+ url: integration.url,
+ permissions,
+ };
+ })
+ .toSorted(
+ (integrationA, integrationB) =>
+ integrationKinds.indexOf(integrationA.kind) - integrationKinds.indexOf(integrationB.kind),
+ );
+};
+
interface IntegrationRouterContext {
db: Database;
session: Parameters[2];
diff --git a/packages/api/src/router/test/app.spec.ts b/packages/api/src/router/test/app.spec.ts
index 3a30bacc9..6706ca6a4 100644
--- a/packages/api/src/router/test/app.spec.ts
+++ b/packages/api/src/router/test/app.spec.ts
@@ -33,7 +33,7 @@ describe("all should return all apps", () => {
const caller = appRouter.createCaller({
db,
deviceType: undefined,
- session: createDefaultSession(),
+ session: createDefaultSession(["app-modify-all"]),
});
await db.insert(apps).values([
@@ -74,6 +74,20 @@ describe("all should return all apps", () => {
// Assert
await expect(actAsync()).rejects.toThrow("UNAUTHORIZED");
});
+ test("should throw FORBIDDEN without app-modify-all permission", async () => {
+ // Arrange
+ const caller = appRouter.createCaller({
+ db: createDb(),
+ deviceType: undefined,
+ session: createDefaultSession(),
+ });
+
+ // Act
+ const actAsync = async () => await caller.all();
+
+ // Assert
+ await expect(actAsync()).rejects.toThrow("Permission denied");
+ });
});
describe("getPaginated should return apps to authenticated users", () => {
@@ -87,12 +101,12 @@ describe("getPaginated should return apps to authenticated users", () => {
await expect(caller.getPaginated({ page: 1, pageSize: 10 })).rejects.toThrow("UNAUTHORIZED");
});
- test("should return apps without board permissions", async () => {
+ test("should return apps with app-modify-all permission", async () => {
const db = createDb();
const caller = appRouter.createCaller({
db,
deviceType: undefined,
- session: createDefaultSession(),
+ session: createDefaultSession(["app-modify-all"]),
});
await db.insert(apps).values({ id: "1", name: "Homarr", iconUrl: "https://homarr.dev/icon.svg" });
@@ -101,6 +115,28 @@ describe("getPaginated should return apps to authenticated users", () => {
items: [{ id: "1" }],
});
});
+
+ test("should throw FORBIDDEN without app-modify-all permission", async () => {
+ const caller = appRouter.createCaller({
+ db: createDb(),
+ deviceType: undefined,
+ session: createDefaultSession(),
+ });
+
+ await expect(caller.getPaginated({ page: 1, pageSize: 10 })).rejects.toThrow("Permission denied");
+ });
+});
+
+describe("search should return apps to authenticated users", () => {
+ test("should throw FORBIDDEN without app-modify-all permission", async () => {
+ const caller = appRouter.createCaller({
+ db: createDb(),
+ deviceType: undefined,
+ session: createDefaultSession(),
+ });
+
+ await expect(caller.search({ query: "Homarr" })).rejects.toThrow("Permission denied");
+ });
});
describe("byId should return an app by id", () => {
diff --git a/packages/api/src/router/test/group.spec.ts b/packages/api/src/router/test/group.spec.ts
index 5deeb3e2f..8af77faa9 100644
--- a/packages/api/src/router/test/group.spec.ts
+++ b/packages/api/src/router/test/group.spec.ts
@@ -449,6 +449,89 @@ describe("savePermissions should save permissions for group", () => {
expect(permissions.map(({ permission }) => permission)).toEqual(["integration-use-all", "board-full-all"]);
});
+ test("with a create permission it should also persist its parent permission", async () => {
+ // Arrange
+ const db = createDb();
+ const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
+
+ const groupId = createId();
+ await db.insert(groups).values({
+ id: groupId,
+ name: "Group",
+ position: 1,
+ });
+
+ // Act
+ await caller.savePermissions({
+ groupId,
+ permissions: ["app-create"],
+ });
+
+ // Assert
+ const permissions = await db.query.groupPermissions.findMany({
+ where: eq(groupPermissions.groupId, groupId),
+ });
+
+ expect(permissions.map(({ permission }) => permission).toSorted()).toEqual(["app-create", "app-modify-all"]);
+ });
+
+ test("with a create permission and its parent it should persist exactly two rows", async () => {
+ // Arrange
+ const db = createDb();
+ const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
+
+ const groupId = createId();
+ await db.insert(groups).values({
+ id: groupId,
+ name: "Group",
+ position: 1,
+ });
+
+ // Act
+ await caller.savePermissions({
+ groupId,
+ permissions: ["app-create", "app-modify-all"],
+ });
+
+ // Assert
+ const permissions = await db.query.groupPermissions.findMany({
+ where: eq(groupPermissions.groupId, groupId),
+ });
+
+ expect(permissions.length).toBe(2);
+ expect(permissions.map(({ permission }) => permission).toSorted()).toEqual(["app-create", "app-modify-all"]);
+ });
+
+ test("with an empty permission list it should clear all existing permissions", async () => {
+ // Arrange
+ const db = createDb();
+ const caller = groupRouter.createCaller({ db, deviceType: undefined, session: adminSession });
+
+ const groupId = createId();
+ await db.insert(groups).values({
+ id: groupId,
+ name: "Group",
+ position: 1,
+ });
+ await db.insert(groupPermissions).values([
+ { groupId, permission: "admin" },
+ { groupId, permission: "board-full-all" },
+ ]);
+
+ // Act
+ await caller.savePermissions({
+ groupId,
+ permissions: [],
+ });
+
+ // Assert
+ const permissions = await db.query.groupPermissions.findMany({
+ where: eq(groupPermissions.groupId, groupId),
+ });
+
+ expect(permissions.length).toBe(0);
+ });
+
test("with non existing group it should throw not found error", async () => {
// Arrange
const db = createDb();
diff --git a/packages/api/src/router/test/integration/integration-router.spec.ts b/packages/api/src/router/test/integration/integration-router.spec.ts
index 1591debb2..fde85f951 100644
--- a/packages/api/src/router/test/integration/integration-router.spec.ts
+++ b/packages/api/src/router/test/integration/integration-router.spec.ts
@@ -58,6 +58,141 @@ describe("all should return all integrations", () => {
expect(result[1]!.kind).toBe("homeAssistant");
expect(result.every(({ permissions }) => permissions.hasFullAccess && permissions.hasUseAccess)).toBe(true);
});
+
+ test("with integration use access should return all integrations", async () => {
+ const db = createDb();
+ const caller = integrationRouter.createCaller({
+ db,
+ deviceType: undefined,
+ session: defaultSessionWithPermissions(["integration-use-all"]),
+ });
+
+ await db.insert(integrations).values([
+ {
+ id: "1",
+ name: "Home assistant",
+ kind: "homeAssistant",
+ url: "http://homeassist.local",
+ },
+ {
+ id: "2",
+ name: "Home plex server",
+ kind: "plex",
+ url: "http://plex.local",
+ },
+ ]);
+
+ const result = await caller.all();
+ expect(result.length).toBe(2);
+ });
+
+ test("without global integration access should only return integrations with use access", async () => {
+ const db = createDb();
+ const caller = integrationRouter.createCaller({
+ db,
+ deviceType: undefined,
+ session: defaultSessionWithPermissions(),
+ });
+
+ await db.insert(integrations).values([
+ {
+ id: "1",
+ name: "Home assistant",
+ kind: "homeAssistant",
+ url: "http://homeassist.local",
+ },
+ {
+ id: "2",
+ name: "Home plex server",
+ kind: "plex",
+ url: "http://plex.local",
+ },
+ ]);
+ await db.insert(users).values({ id: defaultUserId });
+ await db.insert(integrationUserPermissions).values({
+ integrationId: "1",
+ userId: defaultUserId,
+ permission: "use",
+ });
+
+ const result = await caller.all();
+ expect(result).toHaveLength(1);
+ expect(result[0]!.id).toBe("1");
+ expect(result[0]!.permissions.hasUseAccess).toBe(true);
+ });
+
+ test("with a per-integration interact grant should return the integration with use access", async () => {
+ const db = createDb();
+ const caller = integrationRouter.createCaller({
+ db,
+ deviceType: undefined,
+ session: defaultSessionWithPermissions(),
+ });
+
+ await db.insert(integrations).values([
+ {
+ id: "1",
+ name: "Home assistant",
+ kind: "homeAssistant",
+ url: "http://homeassist.local",
+ },
+ {
+ id: "2",
+ name: "Home plex server",
+ kind: "plex",
+ url: "http://plex.local",
+ },
+ ]);
+ await db.insert(users).values({ id: defaultUserId });
+ await db.insert(integrationUserPermissions).values({
+ integrationId: "1",
+ userId: defaultUserId,
+ permission: "interact",
+ });
+
+ const result = await caller.all();
+ expect(result).toHaveLength(1);
+ expect(result[0]!.id).toBe("1");
+ expect(result[0]!.permissions.hasUseAccess).toBe(true);
+ });
+});
+
+describe("search should return accessible integrations", () => {
+ test("without global integration access should only return integrations with use access as plain rows", async () => {
+ const db = createDb();
+ const caller = integrationRouter.createCaller({
+ db,
+ deviceType: undefined,
+ session: defaultSessionWithPermissions(),
+ });
+
+ await db.insert(integrations).values([
+ {
+ id: "1",
+ name: "Home assistant",
+ kind: "homeAssistant",
+ url: "http://homeassist.local",
+ },
+ {
+ id: "2",
+ name: "Home plex server",
+ kind: "plex",
+ url: "http://plex.local",
+ },
+ ]);
+ await db.insert(users).values({ id: defaultUserId });
+ await db.insert(integrationUserPermissions).values({
+ integrationId: "1",
+ userId: defaultUserId,
+ permission: "use",
+ });
+
+ const result = await caller.search({ query: "Home" });
+ expect(result).toHaveLength(1);
+ expect(result[0]!.id).toBe("1");
+ expect(result[0]).not.toHaveProperty("userPermissions");
+ expect(result[0]).not.toHaveProperty("groupPermissions");
+ });
});
describe("mediaRequestSearchTargets should return accessible media search integrations", () => {
diff --git a/packages/definitions/src/permissions.ts b/packages/definitions/src/permissions.ts
index 0ceb648be..3b43d59a5 100644
--- a/packages/definitions/src/permissions.ts
+++ b/packages/definitions/src/permissions.ts
@@ -117,3 +117,44 @@ export const groupPermissionKeys = objectKeys(groupPermissions).reduce((acc, key
}
return acc;
}, [] as GroupPermissionKey[]);
+
+/**
+ * Ordered access levels per category used by the group permission matrix UI.
+ * Each level entry is a full {@link GroupPermissionKey}; higher levels imply the lower ones
+ * through {@link groupPermissionParents}.
+ */
+export const permissionMatrix = {
+ board: { levels: ["board-view-all", "board-modify-all", "board-full-all"] },
+ app: { levels: ["app-use-all", "app-modify-all", "app-full-all"] },
+ integration: { levels: ["integration-use-all", "integration-interact-all", "integration-full-all"] },
+ "search-engine": { levels: ["search-engine-modify-all", "search-engine-full-all"] },
+ media: { levels: ["media-view-all", "media-full-all"] },
+ other: { levels: ["other-view-logs"] },
+ admin: { levels: ["admin"] },
+} as const satisfies Record;
+
+export type PermissionMatrixCategory = keyof typeof permissionMatrix;
+
+export type PermissionMatrixState = Record;
+
+export const permissionsToMatrixState = (permissions: GroupPermissionKey[]): PermissionMatrixState => {
+ const permissionSet = new Set(permissions);
+
+ return objectKeys(permissionMatrix).reduce((acc, category) => {
+ let level = 0;
+ permissionMatrix[category].levels.forEach((key, index) => {
+ if (permissionSet.has(key)) {
+ level = index + 1;
+ }
+ });
+ acc[category] = { level };
+ return acc;
+ }, {} as PermissionMatrixState);
+};
+
+export const matrixStateToPermissions = (state: PermissionMatrixState): GroupPermissionKey[] => {
+ return objectKeys(permissionMatrix).reduce((acc, category) => {
+ acc.push(...permissionMatrix[category].levels.slice(0, state[category].level));
+ return acc;
+ }, [] as GroupPermissionKey[]);
+};
diff --git a/packages/definitions/src/test/permissions.spec.ts b/packages/definitions/src/test/permissions.spec.ts
index 48a4ad665..e74a938f0 100644
--- a/packages/definitions/src/test/permissions.spec.ts
+++ b/packages/definitions/src/test/permissions.spec.ts
@@ -1,7 +1,12 @@
import { describe, expect, test } from "vitest";
import type { GroupPermissionKey } from "../permissions";
-import { getPermissionsWithChildren, getPermissionsWithParents } from "../permissions";
+import {
+ getPermissionsWithChildren,
+ getPermissionsWithParents,
+ matrixStateToPermissions,
+ permissionsToMatrixState,
+} from "../permissions";
describe("getPermissionsWithParents should return the correct permissions", () => {
test.each([
@@ -45,3 +50,70 @@ describe("getPermissionsWithChildren should return the correct permissions", ()
expect(getPermissionsWithChildren(input)).toEqual(expect.arrayContaining(expectedOutput));
});
});
+
+describe("permissionsToMatrixState should resolve the highest present level per category", () => {
+ test("resolves the highest present level key", () => {
+ const state = permissionsToMatrixState(["board-view-all", "board-modify-all"]);
+ expect(state.board.level).toBe(2);
+ });
+
+ test("resolves the admin category", () => {
+ expect(permissionsToMatrixState(["admin"]).admin.level).toBe(1);
+ });
+
+ test("resolves an empty selection to all zero", () => {
+ const state = permissionsToMatrixState([]);
+ expect(Object.values(state).every(({ level }) => level === 0)).toBe(true);
+ });
+});
+
+describe("matrixStateToPermissions should expand levels into permission keys", () => {
+ test("expands a level into the ordered level keys", () => {
+ const permissions = matrixStateToPermissions({
+ board: { level: 2 },
+ app: { level: 0 },
+ integration: { level: 0 },
+ "search-engine": { level: 0 },
+ media: { level: 0 },
+ other: { level: 0 },
+ admin: { level: 0 },
+ });
+ expect(permissions).toEqual(["board-view-all", "board-modify-all"]);
+ });
+
+ test("expands the admin category into the admin key", () => {
+ const permissions = matrixStateToPermissions({
+ board: { level: 0 },
+ app: { level: 0 },
+ integration: { level: 0 },
+ "search-engine": { level: 0 },
+ media: { level: 0 },
+ other: { level: 0 },
+ admin: { level: 1 },
+ });
+ expect(permissions).toEqual(["admin"]);
+ });
+});
+
+describe("matrix helpers should round-trip stably", () => {
+ test.each([
+ [["board-view-all", "board-modify-all"]],
+ [["integration-use-all", "integration-interact-all", "integration-full-all"]],
+ [["admin"]],
+ [[]],
+ [
+ [
+ "app-use-all",
+ "app-modify-all",
+ "search-engine-modify-all",
+ "search-engine-full-all",
+ "media-view-all",
+ "other-view-logs",
+ ],
+ ],
+ ] satisfies [GroupPermissionKey[]][])("expect %s to round-trip", (permissions) => {
+ const roundTripped = matrixStateToPermissions(permissionsToMatrixState(permissions));
+ expect(roundTripped).toEqual(expect.arrayContaining(permissions));
+ expect(roundTripped).toHaveLength(permissions.length);
+ });
+});
diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.json
index 91e4178c5..464dfb114 100644
--- a/packages/translation/src/lang/en.json
+++ b/packages/translation/src/lang/en.json
@@ -653,6 +653,23 @@
"description": "Allow members to manage and delete any search engine"
}
}
+ },
+ "matrix": {
+ "none": "None",
+ "impliedHint": "also grants: {permissions}",
+ "grantedViaAdmin": "Granted via Administrator",
+ "preset": {
+ "label": "Presets",
+ "viewer": "Viewer",
+ "editor": "Editor",
+ "admin": "Admin",
+ "custom": "Custom"
+ },
+ "effective": {
+ "title": "Effective permissions",
+ "description": "Everything members of this group will be able to do, including implied permissions",
+ "empty": "No permissions selected"
+ }
}
},
"memberNotice": {
@@ -1581,6 +1598,7 @@
"title": "Integrations",
"ariaLabel": "Configured integrations",
"search": "Search integrations",
+ "scopedNote": "Showing only integrations you have full access to",
"action": {
"edit": "Edit {name}",
"delete": "Delete {name}"
@@ -1591,7 +1609,9 @@
"action": "Create your first integration",
"filteredTitle": "No integrations match your search",
"filteredDescription": "No integrations match \"{search}\". Try another name, type, or URL.",
- "clearSearch": "Clear search"
+ "clearSearch": "Clear search",
+ "noPermissionTitle": "No manageable integrations",
+ "noPermissionDescription": "You don't have full management access to any integrations. Ask your administrator."
}
},
"create": {
@@ -6134,7 +6154,8 @@
},
"notFound": {
"title": "Not Found",
- "text": "Could not find requested resource"
+ "text": "Could not find requested resource",
+ "backToHome": "Back to management home"
},
"error": {
"title": "This page couldn't load",