Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Add Content Editor share permission (#4421)

Ivan Starkovc3ca454e1f68
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index 7c7a8aeb27..09531cca14 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -31,6 +31,7 @@ import {
$textEditingInstanceSelector,
$isDesignMode,
$isContentMode,
+ $userPlanFeatures,
} from "~/shared/nano-states";
import { $settings, type Settings } from "./shared/client-settings";
import { builderUrl, getCanvasUrl } from "~/shared/router-utils";
@@ -46,7 +47,6 @@ import {
$dataLoadingState,
$isCloneDialogOpen,
$loadingState,
- $userPlanFeatures,
type SidebarPanelName,
} from "./shared/nano-states";
import { CloneProjectDialog } from "~/shared/clone-project";
diff --git a/apps/builder/app/builder/features/pages/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings.tsx
index 3491c8043e..554349c4e0 100644
--- a/apps/builder/app/builder/features/pages/page-settings.tsx
+++ b/apps/builder/app/builder/features/pages/page-settings.tsx
@@ -75,6 +75,7 @@ import {
$dataSourceVariables,
$publishedOrigin,
$project,
+ $userPlanFeatures,
} from "~/shared/nano-states";
import {
BindingControl,
@@ -103,7 +104,6 @@ import {
isPathAvailable,
} from "./page-utils";
import { Form } from "./form";
-import { $userPlanFeatures } from "~/builder/shared/nano-states";
import type { UserPlanFeatures } from "~/shared/db/user-plan-features.server";
import { useUnmount } from "~/shared/hook-utils/use-mount";
import { Card } from "../marketplace/card";
diff --git a/apps/builder/app/builder/features/project-settings/section-general.tsx b/apps/builder/app/builder/features/project-settings/section-general.tsx
index f44cdda137..6695f7b517 100644
--- a/apps/builder/app/builder/features/project-settings/section-general.tsx
+++ b/apps/builder/app/builder/features/project-settings/section-general.tsx
@@ -20,11 +20,15 @@ import { InfoCircleIcon } from "@webstudio-is/icons";
import { ImageControl } from "./image-control";
import { Image } from "@webstudio-is/image";
import type { ProjectMeta } from "@webstudio-is/sdk";
-import { $assets, $imageLoader, $pages } from "~/shared/nano-states";
+import {
+ $assets,
+ $imageLoader,
+ $pages,
+ $userPlanFeatures,
+} from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync";
import { sectionSpacing } from "./utils";
import { CodeEditor } from "~/builder/shared/code-editor";
-import { $userPlanFeatures } from "~/builder/shared/nano-states";
const imgStyle = css({
objectFit: "contain",
diff --git a/apps/builder/app/builder/features/settings-panel/settings-panel.tsx b/apps/builder/app/builder/features/settings-panel/settings-panel.tsx
index 07d1ffd7ef..511657d933 100644
--- a/apps/builder/app/builder/features/settings-panel/settings-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/settings-panel.tsx
@@ -13,9 +13,8 @@ import {
} from "@webstudio-is/design-system";
import { UpgradeIcon } from "@webstudio-is/icons";
import { useStore } from "@nanostores/react";
-import { $userPlanFeatures } from "~/builder/shared/nano-states";
import cmsUpgradeBanner from "./cms-upgrade-banner.svg?url";
-import { $isDesignMode } from "~/shared/nano-states";
+import { $isDesignMode, $userPlanFeatures } from "~/shared/nano-states";
export const SettingsPanelContainer = ({
selectedInstance,
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index 4947718249..a7264d8e92 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -54,9 +54,10 @@ import {
$areResourcesLoading,
invalidateResource,
getComputedResource,
+ $userPlanFeatures,
} from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync";
-import { $userPlanFeatures } from "~/builder/shared/nano-states";
+
import { BindingPopoverProvider } from "~/builder/shared/binding-popover";
import { useSideOffset } from "~/builder/shared/floating-panel";
import {
diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.stories.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.stories.tsx
index 303595f24d..640baf8ace 100644
--- a/apps/builder/app/builder/features/settings-panel/variables-section.stories.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables-section.stories.tsx
@@ -1,9 +1,8 @@
import type { Meta, StoryObj } from "@storybook/react";
import { Box } from "@webstudio-is/design-system";
import { createDefaultPages } from "@webstudio-is/project-build";
-import { $pages, $instances } from "~/shared/nano-states";
+import { $pages, $instances, $userPlanFeatures } from "~/shared/nano-states";
import { registerContainers } from "~/shared/sync";
-import { $userPlanFeatures } from "~/builder/shared/nano-states";
import { $awareness } from "~/shared/awareness";
import { VariablesSection as VariablesSectionComponent } from "./variables-section";
diff --git a/apps/builder/app/builder/features/topbar/domain-checkbox.tsx b/apps/builder/app/builder/features/topbar/domain-checkbox.tsx
index cb8e986fa1..c68aeae817 100644
--- a/apps/builder/app/builder/features/topbar/domain-checkbox.tsx
+++ b/apps/builder/app/builder/features/topbar/domain-checkbox.tsx
@@ -8,8 +8,8 @@ import {
buttonStyle,
Checkbox,
} from "@webstudio-is/design-system";
-import { $userPlanFeatures } from "~/builder/shared/nano-states";
-import { $project } from "~/shared/nano-states";
+
+import { $project, $userPlanFeatures } from "~/shared/nano-states";
export const domainToPublishName = "domainToPublish[]";
diff --git a/apps/builder/app/builder/features/topbar/menu/menu.tsx b/apps/builder/app/builder/features/topbar/menu/menu.tsx
index 7f21981d0a..1f2210b390 100644
--- a/apps/builder/app/builder/features/topbar/menu/menu.tsx
+++ b/apps/builder/app/builder/features/topbar/menu/menu.tsx
@@ -16,7 +16,6 @@ import {
menuItemCss,
} from "@webstudio-is/design-system";
import {
- $userPlanFeatures,
$isCloneDialogOpen,
$isShareDialogOpen,
$isPublishDialogOpen,
@@ -26,6 +25,7 @@ import {
$authPermit,
$authToken,
$authTokenPermissions,
+ $userPlanFeatures,
} from "~/shared/nano-states";
import { emitCommand } from "~/builder/shared/commands";
import { MenuButton } from "./menu-button";
diff --git a/apps/builder/app/builder/features/topbar/publish.tsx b/apps/builder/app/builder/features/topbar/publish.tsx
index f3c543ad66..4cef25ca12 100644
--- a/apps/builder/app/builder/features/topbar/publish.tsx
+++ b/apps/builder/app/builder/features/topbar/publish.tsx
@@ -35,12 +35,14 @@ import {
RadioGroup,
} from "@webstudio-is/design-system";
import stripIndent from "strip-indent";
+import { $isPublishDialogOpen } from "../../shared/nano-states";
+import { validateProjectDomain, type Project } from "@webstudio-is/project";
import {
- $isPublishDialogOpen,
+ $authPermit,
+ $project,
+ $publishedOrigin,
$userPlanFeatures,
-} from "../../shared/nano-states";
-import { validateProjectDomain, type Project } from "@webstudio-is/project";
-import { $authPermit, $project, $publishedOrigin } from "~/shared/nano-states";
+} from "~/shared/nano-states";
import { Domains, PENDING_TIMEOUT, getPublishStatusAndText } from "./domains";
import { CollapsibleDomainSection } from "./collapsible-domain-section";
import {
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index be15992b73..3084a8accf 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -6,6 +6,8 @@ import {
$textEditingInstanceSelector,
$builderMode,
$isDesignMode,
+ $isDesignModeAllowed,
+ setBuilderMode,
} from "~/shared/nano-states";
import {
$breakpointsMenuView,
@@ -131,10 +133,15 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
handler: () => {
setActiveSidebarPanel("auto");
+ // @todo: This is temporary until we have a combo to switch modes
if ($builderMode.get() === "preview") {
- $builderMode.set("design");
+ if ($isDesignModeAllowed.get()) {
+ setBuilderMode("design");
+ } else {
+ setBuilderMode("content");
+ }
} else {
- $builderMode.set("preview");
+ setBuilderMode("preview");
}
},
},
@@ -144,10 +151,15 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
handler: () => {
setActiveSidebarPanel("auto");
+ // @todo: This is temporary until we have a combo to switch modes
if ($builderMode.get() === "content") {
- $builderMode.set("design");
+ if ($isDesignModeAllowed.get()) {
+ setBuilderMode("design");
+ } else {
+ setBuilderMode("preview");
+ }
} else {
- $builderMode.set("content");
+ setBuilderMode("content");
}
},
},
diff --git a/apps/builder/app/builder/shared/nano-states/index.ts b/apps/builder/app/builder/shared/nano-states/index.ts
index 2b05addd99..5ac9ed5180 100644
--- a/apps/builder/app/builder/shared/nano-states/index.ts
+++ b/apps/builder/app/builder/shared/nano-states/index.ts
@@ -1,5 +1,4 @@
import { atom, computed } from "nanostores";
-import type { UserPlanFeatures } from "~/shared/db/user-plan-features.server";
import {
$isPreviewMode,
$selectedInstanceRenderState,
@@ -37,16 +36,6 @@ export const $scale = computed(
export const $activeInspectorPanel = atom<"style" | "settings">("style");
-// keep in sync with user-plan-features.server
-export const $userPlanFeatures = atom<UserPlanFeatures>({
- allowShareAdminLinks: false,
- allowDynamicData: false,
- maxContactEmails: 0,
- maxDomainsAllowedPerUser: 1,
- hasSubscription: false,
- hasProPlan: false,
-});
-
export const $dataLoadingState = atom<"idle" | "loading" | "loaded">("idle");
export const $loadingState = computed(
diff --git a/apps/builder/app/routes/_ui.(builder).tsx b/apps/builder/app/routes/_ui.(builder).tsx
index f8882463ba..454fe64cde 100644
--- a/apps/builder/app/routes/_ui.(builder).tsx
+++ b/apps/builder/app/routes/_ui.(builder).tsx
@@ -134,7 +134,7 @@ export const loader = async (loaderArgs: LoaderFunctionArgs) => {
projectId: project.id,
// At this point we already knew that if project loaded we have at least "view" permit
// having that getProjectPermit is heavy operation we can skip check "view" permit
- permits: ["own", "admin", "build"] as const,
+ permits: ["own", "admin", "build", "edit"] as const,
},
context
)) ?? "view";
diff --git a/apps/builder/app/routes/rest.patch.ts b/apps/builder/app/routes/rest.patch.ts
index aff5be010f..d85ce4739b 100644
--- a/apps/builder/app/routes/rest.patch.ts
+++ b/apps/builder/app/routes/rest.patch.ts
@@ -119,17 +119,23 @@ export const action = async ({
};
}
- const canEdit = await authorizeProject.hasProjectPermit(
- { projectId, permit: "edit" },
- context
- );
- if (canEdit === false) {
+ const [canEditContent, canEdit] = await Promise.all([
+ authorizeProject.hasProjectPermit({ projectId, permit: "edit" }, context),
+ authorizeProject.hasProjectPermit(
+ { projectId, permit: "build" },
+ context
+ ),
+ ]);
+
+ if (canEditContent === false) {
return {
status: "authorization_error",
errors: "You don't have permission to edit this project.",
};
}
+ const isContentEditMode = canEditContent && !canEdit;
+
const build = await loadRawBuildById(context, buildId);
const serverVersion = build.version;
@@ -209,6 +215,29 @@ export const action = async ({
continue;
}
+ if (namespace === "props") {
+ const props = buildData.props ?? parseData<Prop>(build.props);
+ buildData.props = applyPatches(props, patches);
+ continue;
+ }
+
+ if (namespace === "assets") {
+ // assets implements own patching
+ // @todo parallelize the updates
+ // currently not possible because we fetch the entire tree
+ // and parallelized updates will cause unpredictable side effects
+ await patchAssets({ projectId }, patches, context);
+ continue;
+ }
+
+ // This is super simple and naive implementation of permissions checks for Content Edit mode
+ if (isContentEditMode) {
+ return {
+ status: "error",
+ errors: `You don't have permission to patch namespace ${namespace}`,
+ };
+ }
+
if (namespace === "styleSourceSelections") {
const styleSourceSelections =
buildData.styleSourceSelections ??
@@ -239,12 +268,6 @@ export const action = async ({
continue;
}
- if (namespace === "props") {
- const props = buildData.props ?? parseData<Prop>(build.props);
- buildData.props = applyPatches(props, patches);
- continue;
- }
-
if (namespace === "dataSources") {
const dataSources =
buildData.dataSources ?? parseData<DataSource>(build.dataSources);
@@ -266,15 +289,6 @@ export const action = async ({
continue;
}
- if (namespace === "assets") {
- // assets implements own patching
- // @todo parallelize the updates
- // currently not possible because we fetch the entire tree
- // and parallelized updates will cause unpredictable side effects
- await patchAssets({ projectId }, patches, context);
- continue;
- }
-
if (namespace === "marketplaceProduct") {
const marketplaceProduct =
buildData.marketplaceProduct ??
diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.ts
index 0a8d87ffce..fe8e0b6900 100644
--- a/apps/builder/app/shared/nano-states/misc.ts
+++ b/apps/builder/app/shared/nano-states/misc.ts
@@ -1,7 +1,7 @@
import { atom, computed, onSet } from "nanostores";
import { nanoid } from "nanoid";
import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";
-import type { Placement } from "@webstudio-is/design-system";
+import { toast, type Placement } from "@webstudio-is/design-system";
import type {
Assets,
DataSources,
@@ -29,6 +29,7 @@ import type { Simplify } from "type-fest";
import type { AssetType } from "@webstudio-is/asset-uploader";
import type { ChildrenOrientation } from "node_modules/@webstudio-is/design-system/src/components/primitives/dnd/geometry-utils";
import { $selectedInstance } from "../awareness";
+import type { UserPlanFeatures } from "../db/user-plan-features.server";
export const $project = atom<Project | undefined>();
@@ -297,6 +298,16 @@ export const $hoveredInstanceSelector = atom<undefined | InstanceSelector>(
undefined
);
+// keep in sync with user-plan-features.server
+export const $userPlanFeatures = atom<UserPlanFeatures>({
+ allowShareAdminLinks: false,
+ allowDynamicData: false,
+ maxContactEmails: 0,
+ maxDomainsAllowedPerUser: 1,
+ hasSubscription: false,
+ hasProPlan: false,
+});
+
const builderModes = ["design", "preview", "content"] as const;
export type BuilderMode = (typeof builderModes)[number];
export const isBuilderMode = (mode: string | null): mode is BuilderMode =>
@@ -324,6 +335,57 @@ export const $authTokenPermissions = atom<TokenPermissions>({
export const $authToken = atom<string | undefined>(undefined);
+export const $isContentModeAllowed = computed(
+ [$authToken, $userPlanFeatures],
+ (token, userPlanFeatures) => {
+ // In own projects, everyone can edit content
+ if (token === undefined) {
+ return true;
+ }
+
+ // In shared projects, only Pro users can share editable links, so check the plan features of the user who shared the link
+ return userPlanFeatures.hasProPlan === true;
+ }
+);
+
+export const $isDesignModeAllowed = computed([$authPermit], (authPermit) => {
+ return authPermit !== "edit";
+});
+
+export const setBuilderMode = (mode: BuilderMode | null) => {
+ const authPermit = $authPermit.get();
+
+ if (mode === "content" && !$isContentModeAllowed.get()) {
+ // This is content link from a non pro user, we don't allow content mode for such links
+ toast.error(
+ "Content mode is not available for this link. The link’s author must have a Pro plan."
+ );
+
+ $builderMode.set("preview");
+ return;
+ }
+
+ if (mode === "design" && !$isDesignModeAllowed.get()) {
+ toast.error("Design mode is not available for content edit links.");
+
+ $builderMode.set("content");
+ return;
+ }
+
+ if (authPermit === "view") {
+ $builderMode.set(mode ?? "preview");
+ return;
+ }
+
+ const defaultMode = $isDesignModeAllowed.get()
+ ? "design"
+ : $isContentModeAllowed.get()
+ ? "content"
+ : "preview";
+
+ $builderMode.set(mode ?? defaultMode);
+};
+
export const $toastErrors = atom<string[]>([]);
export type ItemDropTarget = {
diff --git a/apps/builder/app/shared/pages/use-switch-page.ts b/apps/builder/app/shared/pages/use-switch-page.ts
index 23e2d5715c..c9f3b46160 100644
--- a/apps/builder/app/shared/pages/use-switch-page.ts
+++ b/apps/builder/app/shared/pages/use-switch-page.ts
@@ -8,7 +8,7 @@ import {
$selectedPageHash,
$builderMode,
isBuilderMode,
- $isPreviewMode,
+ setBuilderMode,
} from "~/shared/nano-states";
import { builderPath } from "~/shared/router-utils";
import { $selectedPage, selectPage } from "../awareness";
@@ -30,7 +30,7 @@ const setPageStateFromUrl = () => {
`Invalid search param mode: ${mode}`
);
- $builderMode.set(isBuilderMode(mode) ? mode : "design");
+ setBuilderMode(mode);
$selectedPageHash.set(searchParams.get("pageHash") ?? "");
selectPage(pageId);
@@ -49,7 +49,7 @@ export const useSyncPageUrl = () => {
const navigate = useNavigate();
const page = useStore($selectedPage);
const pageHash = useStore($selectedPageHash);
- const isPreviewMode = useStore($isPreviewMode);
+ const builderMode = useStore($builderMode);
// Get pageId and pageHash from URL
// once pages are loaded
@@ -82,13 +82,16 @@ export const useSyncPageUrl = () => {
const searchParamsPageId = searchParams.get("pageId") ?? pages.homePage.id;
const searchParamsPageHash = searchParams.get("pageHash") ?? "";
- const searchParamsIsPreviewMode = searchParams.get("mode") === "preview";
+ const searParamsModeRaw = searchParams.get("mode");
+ const searParamsMode = isBuilderMode(searParamsModeRaw)
+ ? searParamsModeRaw
+ : undefined;
// Do not navigate on popstate change
if (
searchParamsPageId === page.id &&
searchParamsPageHash === pageHash &&
- searchParamsIsPreviewMode === isPreviewMode
+ searParamsMode === builderMode
) {
return;
}
@@ -98,10 +101,10 @@ export const useSyncPageUrl = () => {
pageId: page.id === pages.homePage.id ? undefined : page.id,
authToken: $authToken.get(),
pageHash: pageHash === "" ? undefined : pageHash,
- mode: isPreviewMode ? "preview" : undefined,
+ mode: builderMode === "design" ? undefined : builderMode,
})
);
- }, [isPreviewMode, navigate, page, pageHash]);
+ }, [builderMode, navigate, page, pageHash]);
};
/**
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index def2bdfd85..8f88a3b722 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -23,7 +23,7 @@ export const builderPath = ({
pageId?: string;
authToken?: string;
pageHash?: string;
- mode?: "preview";
+ mode?: "preview" | "content";
}) => {
return `/${searchParams({
pageId,
diff --git a/apps/builder/app/shared/share-project/share-project.tsx b/apps/builder/app/shared/share-project/share-project.tsx
index 4dc93fdef7..18bcf19ff7 100644
--- a/apps/builder/app/shared/share-project/share-project.tsx
+++ b/apps/builder/app/shared/share-project/share-project.tsx
@@ -32,6 +32,8 @@ import {
import { Fragment, useState, type ComponentProps, type ReactNode } from "react";
import { useIds } from "../form-utils";
import { CopyToClipboard } from "~/builder/shared/copy-to-clipboard";
+import { isFeatureEnabled } from "@webstudio-is/feature-flags";
+import type { BuilderMode } from "../nano-states";
const Item = (props: ComponentProps<typeof Flex>) => (
<Flex
@@ -225,6 +227,39 @@ const Menu = ({ name, hasProPlan, value, onChange, onDelete }: MenuProps) => {
</Grid>
</Grid>
+ {isFeatureEnabled("contentEditableMode") && (
+ <Permission
+ disabled={hasProPlan !== true}
+ onCheckedChange={handleCheckedChange("editors")}
+ checked={value.relation === "editors"}
+ title="Content"
+ info={
+ <Flex direction="column">
+ Recipients can edit content only, such as text, images, and
+ predefined components.
+ {hasProPlan !== true && (
+ <>
+ <br />
+ <br />
+ Upgrade to a Pro account to share with Content Edit
+ permissions.
+ <br /> <br />
+ <Link
+ className={buttonStyle({ color: "gradient" })}
+ color="contrast"
+ underline="none"
+ href="https://webstudio.is/pricing"
+ target="_blank"
+ >
+ Upgrade
+ </Link>
+ </>
+ )}
+ </Flex>
+ }
+ />
+ )}
+
<Permission
onCheckedChange={handleCheckedChange("builders")}
checked={value.relation === "builders"}
@@ -301,13 +336,17 @@ type SharedLinkItemType = {
value: LinkOptions;
onChange: (value: LinkOptions) => void;
onDelete: () => void;
- builderUrl: (props: {
- authToken: string;
- mode: "preview" | "design";
- }) => string;
+ builderUrl: (props: { authToken: string; mode: BuilderMode }) => string;
hasProPlan: boolean;
};
+const relationToMode: Record<Relation, BuilderMode> = {
+ viewers: "preview",
+ editors: "content",
+ builders: "design",
+ administrators: "design",
+};
+
const SharedLinkItem = ({
value,
onChange,
@@ -323,7 +362,7 @@ const SharedLinkItem = ({
<CopyToClipboard
text={builderUrl({
authToken: value.token,
- mode: value.relation === "viewers" ? "preview" : "design",
+ mode: relationToMode[value.relation],
})}
copyText="Copy link"
>
diff --git a/packages/authorization-token/package.json b/packages/authorization-token/package.json
index 1b9ff7535a..83e9e41cad 100644
--- a/packages/authorization-token/package.json
+++ b/packages/authorization-token/package.json
@@ -15,7 +15,8 @@
},
"devDependencies": {
"@webstudio-is/tsconfig": "workspace:*",
- "typescript": "5.6.3"
+ "typescript": "5.6.3",
+ "type-fest": "^4.26.1"
},
"exports": {
".": {
diff --git a/packages/authorization-token/src/trpc/authorization-tokens-router.ts b/packages/authorization-token/src/trpc/authorization-tokens-router.ts
index 7f6a24cf51..8e8f75805c 100644
--- a/packages/authorization-token/src/trpc/authorization-tokens-router.ts
+++ b/packages/authorization-token/src/trpc/authorization-tokens-router.ts
@@ -1,6 +1,11 @@
import { z } from "zod";
import { router, procedure } from "@webstudio-is/trpc-interface/index.server";
import { db } from "../db";
+import type { IsEqual } from "type-fest";
+import type { Database } from "@webstudio-is/postrest/index.server";
+
+type Relation =
+ Database["public"]["Tables"]["AuthorizationToken"]["Row"]["relation"];
const TokenProjectRelation = z.enum([
"viewers",
@@ -9,6 +14,10 @@ const TokenProjectRelation = z.enum([
"administrators",
]);
+// Check DB types are compatible with zod types
+type TokenRelation = z.infer<typeof TokenProjectRelation>;
+true satisfies IsEqual<TokenRelation, Relation>;
+
export const authorizationTokenRouter = router({
findMany: procedure
.input(
diff --git a/packages/trpc-interface/src/authorize/project.server.ts b/packages/trpc-interface/src/authorize/project.server.ts
index 5fcc4be70e..30e5b5e7ed 100644
--- a/packages/trpc-interface/src/authorize/project.server.ts
+++ b/packages/trpc-interface/src/authorize/project.server.ts
@@ -1,8 +1,14 @@
import type { AppContext } from "../context/context.server";
+import type { Database } from "@webstudio-is/postrest/index.server";
import memoize from "memoize";
+type Relation =
+ Database["public"]["Tables"]["AuthorizationToken"]["Row"]["relation"];
+
export type AuthPermit = "view" | "edit" | "build" | "admin" | "own";
+type TokenAuthPermit = Exclude<AuthPermit, "own">;
+
type CheckInput = {
namespace: "Project";
id: string;
@@ -36,28 +42,33 @@ const check = async (
return { allowed: row.data !== null };
}
- const permitToRelationRewrite = {
+ if (input.permit === "own") {
+ return { allowed: false };
+ }
+
+ if (subjectSet.namespace !== "Token") {
+ return { allowed: false };
+ }
+
+ const permitToRelationRewrite: Record<TokenAuthPermit, Relation[]> = {
view: ["viewers", "editors", "builders", "administrators"],
edit: ["editors", "builders", "administrators"],
build: ["builders", "administrators"],
admin: ["administrators"],
- } as const;
+ };
- if (subjectSet.namespace === "Token" && input.permit !== "own") {
- const row = await postgrestClient
- .from("AuthorizationToken")
- .select("token")
- .eq("token", subjectSet.id)
- .in("relation", [...permitToRelationRewrite[input.permit]])
- .maybeSingle();
- if (row.error) {
- throw row.error;
- }
+ const row = await postgrestClient
+ .from("AuthorizationToken")
+ .select("token")
+ .eq("token", subjectSet.id)
+ .in("relation", [...permitToRelationRewrite[input.permit]])
+ .maybeSingle();
- return { allowed: row.data !== null };
+ if (row.error) {
+ throw row.error;
}
- return { allowed: false };
+ return { allowed: row.data !== null };
};
// doesn't work in cloudflare workers
@@ -196,13 +207,13 @@ export const hasProjectPermit = async (
* @todo think about caching to authorizeTrpc.check.query
* batching check queries would help too https://github.com/ory/keto/issues/812
*/
-export const getProjectPermit = async <T extends AuthPermit>(
+export const getProjectPermit = async (
props: {
projectId: string;
- permits: readonly T[];
+ permits: readonly AuthPermit[];
},
context: AppContext
-): Promise<T | undefined> => {
+): Promise<AuthPermit | undefined> => {
const permitToCheck = props.permits;
const permits = await Promise.allSettled(
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d90efcd953..4075be9c95 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1014,6 +1014,9 @@ importers:
'@webstudio-is/tsconfig':
specifier: workspace:*
version: link:../tsconfig
+ type-fest:
+ specifier: ^4.26.1
+ version: 4.26.1
typescript:
specifier: 5.6.3
version: 5.6.3