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.

fix: Project Cloning Broken for Share Links (#4071)

Ivan Starkov50ff477c971d
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index 40558d26a5..910cb7387f 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -31,7 +31,7 @@ import {
$textEditingInstanceSelector,
} from "~/shared/nano-states";
import { $settings, type Settings } from "./shared/client-settings";
-import { getCanvasUrl } from "~/shared/router-utils";
+import { builderUrl, getCanvasUrl } from "~/shared/router-utils";
import { useCopyPaste } from "~/shared/copy-paste";
import { BlockingAlerts } from "./features/blocking-alerts";
import { useSyncPageUrl } from "~/shared/pages";
@@ -400,6 +400,12 @@ export const Builder = ({
isOpen={isCloneDialogOpen}
onOpenChange={$isCloneDialogOpen.set}
project={project}
+ onCreate={(projectId) => {
+ window.location.href = builderUrl({
+ origin: window.origin,
+ projectId: projectId,
+ });
+ }}
/>
</ChromeWrapper>
<Loading state={loadingState} />
diff --git a/apps/builder/app/builder/features/topbar/clone.tsx b/apps/builder/app/builder/features/topbar/clone.tsx
new file mode 100644
index 0000000000..2c50201f7b
--- /dev/null
+++ b/apps/builder/app/builder/features/topbar/clone.tsx
@@ -0,0 +1,30 @@
+import { useStore } from "@nanostores/react";
+import { buttonStyle, Link } from "@webstudio-is/design-system";
+import { $authToken, $authTokenPermissions } from "~/shared/nano-states";
+import { cloneProjectUrl } from "~/shared/router-utils/path-utils";
+
+export const CloneButton = () => {
+ const authTokenPermission = useStore($authTokenPermissions);
+ const authToken = useStore($authToken);
+
+ if (authToken === undefined || false === authTokenPermission.canClone) {
+ return;
+ }
+
+ return (
+ <Link
+ data-state="auto"
+ className={buttonStyle({
+ color: "positive",
+ })}
+ color="contrast"
+ href={cloneProjectUrl({
+ origin: window.origin,
+ sourceAuthToken: authToken,
+ })}
+ underline="none"
+ >
+ Clone
+ </Link>
+ );
+};
diff --git a/apps/builder/app/builder/features/topbar/menu/menu.tsx b/apps/builder/app/builder/features/topbar/menu/menu.tsx
index 4da5da70d0..fc12d775d9 100644
--- a/apps/builder/app/builder/features/topbar/menu/menu.tsx
+++ b/apps/builder/app/builder/features/topbar/menu/menu.tsx
@@ -13,6 +13,7 @@ import {
DropdownMenuPortal,
Tooltip,
Kbd,
+ menuItemCss,
} from "@webstudio-is/design-system";
import {
$userPlanFeatures,
@@ -20,8 +21,12 @@ import {
$isShareDialogOpen,
$isPublishDialogOpen,
} from "~/builder/shared/nano-states";
-import { dashboardUrl } from "~/shared/router-utils";
-import { $authPermit, $authTokenPermissions } from "~/shared/nano-states";
+import { cloneProjectUrl, dashboardUrl } from "~/shared/router-utils";
+import {
+ $authPermit,
+ $authToken,
+ $authTokenPermissions,
+} from "~/shared/nano-states";
import { emitCommand } from "~/builder/shared/commands";
import { MenuButton } from "./menu-button";
import { $isProjectSettingsOpen } from "~/shared/nano-states/seo";
@@ -54,6 +59,7 @@ export const Menu = () => {
const { hasProPlan } = useStore($userPlanFeatures);
const authPermit = useStore($authPermit);
const authTokenPermission = useStore($authTokenPermissions);
+ const authToken = useStore($authToken);
const isPublishEnabled = authPermit === "own" || authPermit === "admin";
@@ -67,6 +73,9 @@ export const Menu = () => {
? undefined
: "Only owner can share projects";
+ // If authToken is defined, the user is not logged into the current project and must be redirected to the dashboard to clone the project.
+ const cloneIsExternal = authToken !== undefined;
+
return (
<DropdownMenu>
<MenuButton />
@@ -184,11 +193,27 @@ export const Menu = () => {
>
<DropdownMenuItem
onSelect={() => {
- $isCloneDialogOpen.set(true);
+ if ($authToken.get() === undefined) {
+ $isCloneDialogOpen.set(true);
+ return;
+ }
}}
disabled={authTokenPermission.canClone === false}
+ asChild={cloneIsExternal}
>
- Clone
+ {cloneIsExternal ? (
+ <a
+ className={menuItemCss()}
+ href={cloneProjectUrl({
+ origin: window.origin,
+ sourceAuthToken: authToken,
+ })}
+ >
+ Clone
+ </a>
+ ) : (
+ "Clone"
+ )}
</DropdownMenuItem>
</Tooltip>
diff --git a/apps/builder/app/builder/features/topbar/topbar.tsx b/apps/builder/app/builder/features/topbar/topbar.tsx
index 293505f3b8..b28b4873d7 100644
--- a/apps/builder/app/builder/features/topbar/topbar.tsx
+++ b/apps/builder/app/builder/features/topbar/topbar.tsx
@@ -24,6 +24,7 @@ import { ViewMode } from "./view-mode";
import { AddressBarPopover } from "../address-bar";
import { toggleActiveSidebarPanel } from "~/builder/shared/nano-states";
import type { ReactNode } from "react";
+import { CloneButton } from "./clone";
const PagesButton = () => {
const page = useStore($selectedPage);
@@ -113,6 +114,7 @@ export const Topbar = ({ project, hasProPlan, css, loading }: TopbarProps) => {
<PreviewButton />
<ShareButton projectId={project.id} hasProPlan={hasProPlan} />
<PublishButton projectId={project.id} />
+ <CloneButton />
</ToolbarToggleGroup>
</Toolbar>
{loading}
diff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsx
index f1b5210d3b..7a024aa18e 100644
--- a/apps/builder/app/dashboard/dashboard.tsx
+++ b/apps/builder/app/dashboard/dashboard.tsx
@@ -1,4 +1,4 @@
-import type { ComponentProps } from "react";
+import { useEffect, useState, type ComponentProps } from "react";
import {
Flex,
TooltipProvider,
@@ -11,6 +11,9 @@ import { Projects } from "./projects";
import type { User } from "~/shared/db/user.server";
import type { UserPlanFeatures } from "~/shared/db/user-plan-features.server";
import { Resources } from "./resources";
+import { useLocation, useRevalidator } from "@remix-run/react";
+import { CloneProjectDialog } from "~/shared/clone-project";
+import { Toaster } from "@webstudio-is/design-system";
const globalStyles = globalCss({
body: {
@@ -49,6 +52,48 @@ export type DashboardProps = {
userPlanFeatures: UserPlanFeatures;
publisherHost: string;
imageBaseUrl: string;
+ projectToClone?: {
+ authToken: string;
+ id: string;
+ title: string;
+ };
+};
+
+const CloneProject = ({
+ projectToClone,
+}: {
+ projectToClone: DashboardProps["projectToClone"];
+}) => {
+ const location = useLocation();
+ const [isOpen, setIsOpen] = useState(projectToClone !== undefined);
+ const { revalidate } = useRevalidator();
+
+ useEffect(() => {
+ const searchParams = new URLSearchParams(location.search);
+ const cloneProjectAuthToken = searchParams.get("projectToCloneAuthToken");
+ if (cloneProjectAuthToken === null) {
+ return;
+ }
+
+ // Use the native history API to remove query parameters without reloading the page data
+ const currentState = window.history.state;
+ window.history.replaceState(currentState, "", location.pathname);
+ }, [location.search, location.pathname]);
+
+ return projectToClone !== undefined ? (
+ <CloneProjectDialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ project={{
+ id: projectToClone.id,
+ title: projectToClone.title,
+ }}
+ authToken={projectToClone.authToken}
+ onCreate={() => {
+ revalidate();
+ }}
+ />
+ ) : undefined;
};
export const Dashboard = ({
@@ -58,8 +103,10 @@ export const Dashboard = ({
userPlanFeatures,
publisherHost,
imageBaseUrl,
+ projectToClone,
}: DashboardProps) => {
globalStyles();
+
return (
<TooltipProvider>
<Header user={user} userPlanFeatures={userPlanFeatures} />
@@ -77,6 +124,8 @@ export const Dashboard = ({
/>
</Section>
</Main>
+ <CloneProject projectToClone={projectToClone} />
+ <Toaster />
</TooltipProvider>
);
};
diff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsx
index 73b1d2a754..0a2e725d37 100644
--- a/apps/builder/app/dashboard/projects/project-card.tsx
+++ b/apps/builder/app/dashboard/projects/project-card.tsx
@@ -350,6 +350,12 @@ export const ProjectTemplateCard = ({
isOpen={isDuplicateDialogOpen}
onOpenChange={setIsDuplicateDialogOpen}
project={project}
+ onCreate={(projectId) => {
+ window.location.href = builderUrl({
+ origin: window.origin,
+ projectId: projectId,
+ });
+ }}
/>
</Card>
);
diff --git a/apps/builder/app/routes/_ui.(builder).tsx b/apps/builder/app/routes/_ui.(builder).tsx
index 6179ee1b09..6a7db83ff3 100644
--- a/apps/builder/app/routes/_ui.(builder).tsx
+++ b/apps/builder/app/routes/_ui.(builder).tsx
@@ -83,18 +83,17 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const context = await createContext(request);
- if (
- context.authorization.userId === undefined &&
- context.authorization.authToken === undefined
- ) {
+ if (context.authorization.type === "service") {
+ throw new AuthorizationError("Service calls are not allowed");
+ }
+
+ if (context.authorization.type === "anonymous") {
// @todo just import loader from auth and call it
throw redirect("/auth/ws");
}
if (
- context.authorization.authToken === undefined &&
- context.authorization.userId !== undefined &&
- context.authorization.sessionCreatedAt !== undefined &&
+ context.authorization.type === "user" &&
request.headers.get("sec-fetch-mode") === "navigate"
) {
// If logout fails, or the session cookie in the dashboard is deleted or expired,
@@ -179,7 +178,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const headers = new Headers();
- if (context.authorization.authToken !== undefined) {
+ if (context.authorization.type === "token") {
// To protect against cookie overwrites, we set a null session cookie if a user is using an authToken.
// This ensures that any existing HttpOnly, secure session cookies cannot be overwritten by client-side scripts
diff --git a/apps/builder/app/routes/_ui.dashboard.tsx b/apps/builder/app/routes/_ui.dashboard.tsx
index 8a2d72acfc..f5742081e6 100644
--- a/apps/builder/app/routes/_ui.dashboard.tsx
+++ b/apps/builder/app/routes/_ui.dashboard.tsx
@@ -8,11 +8,16 @@ import { createContext } from "~/shared/context.server";
import env from "~/env/env.server";
import { ClientOnly } from "~/shared/client-only";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-import { createCallerFactory } from "@webstudio-is/trpc-interface/index.server";
+import {
+ AuthorizationError,
+ createCallerFactory,
+} from "@webstudio-is/trpc-interface/index.server";
import { redirect } from "~/services/no-store-redirect";
import { preconnect, prefetchDNS } from "react-dom";
import { parseBuilderUrl } from "@webstudio-is/http-client";
import { allowedDestinations } from "~/services/destinations.server";
+import { db as authDb } from "@webstudio-is/authorization-token/index.server";
+import { db } from "@webstudio-is/project/index.server";
const dashboardProjectCaller = createCallerFactory(dashboardProjectRouter);
@@ -40,17 +45,55 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const user = await findAuthenticatedUser(request);
+ const url = new URL(request.url);
+
if (user === null) {
- const url = new URL(request.url);
throw redirect(
loginPath({
- returnTo: url.pathname,
+ returnTo: `${url.pathname}${url.search}`,
})
);
}
const context = await createContext(request);
+ if (context.authorization.type !== "user") {
+ throw new AuthorizationError("You must be logged in to access this page");
+ }
+
+ const projectToCloneAuthToken = url.searchParams.get(
+ "projectToCloneAuthToken"
+ );
+
+ let projectToClone:
+ | { id: string; title: string; authToken: string }
+ | undefined = undefined;
+
+ if (
+ // Only on navigation requests
+ request.headers.get("sec-fetch-mode") === "navigate" &&
+ projectToCloneAuthToken !== null
+ ) {
+ // Clone project
+ const token = await authDb.getTokenInfo(projectToCloneAuthToken, context);
+ if (token.canClone === false) {
+ throw new AuthorizationError(
+ "You don't have access to clone this project"
+ );
+ }
+
+ const project = await db.project.loadById(
+ token.projectId,
+ await context.createTokenContext(projectToCloneAuthToken)
+ );
+
+ projectToClone = {
+ id: token.projectId,
+ authToken: projectToCloneAuthToken,
+ title: project.title,
+ };
+ }
+
const projects = await dashboardProjectCaller(context).findMany({
userId: user.id,
});
@@ -75,6 +118,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
publisherHost: env.PUBLISHER_HOST,
imageBaseUrl: env.IMAGE_BASE_URL,
origin: sourceOrigin,
+ projectToClone,
});
};
diff --git a/apps/builder/app/routes/_ui.logout.tsx b/apps/builder/app/routes/_ui.logout.tsx
index 5513a8641c..686cd7ae24 100644
--- a/apps/builder/app/routes/_ui.logout.tsx
+++ b/apps/builder/app/routes/_ui.logout.tsx
@@ -39,8 +39,8 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const redirectTo = loginPath({});
- if (context.authorization.userId === undefined) {
- debug("User is not logged in redirecting to", redirectTo);
+ if (context.authorization.type !== "user") {
+ debug("User is not logged in, redirecting to", redirectTo);
throw redirect(redirectTo);
}
diff --git a/apps/builder/app/routes/oauth.ws.authorize.tsx b/apps/builder/app/routes/oauth.ws.authorize.tsx
index 6c4a6295db..f77252ac97 100644
--- a/apps/builder/app/routes/oauth.ws.authorize.tsx
+++ b/apps/builder/app/routes/oauth.ws.authorize.tsx
@@ -237,7 +237,7 @@ export const loader: LoaderFunction = async ({ request }) => {
const bloomFilter = await session.readLoginSessionBloomFilter(request);
- await bloomFilter.add(oAuthParams.scope.projectId);
+ bloomFilter.add(oAuthParams.scope.projectId);
return session.writeLoginSessionBloomFilter(
request,
diff --git a/apps/builder/app/routes/rest.ai._index.ts b/apps/builder/app/routes/rest.ai._index.ts
index d5a260c137..f005197a36 100644
--- a/apps/builder/app/routes/rest.ai._index.ts
+++ b/apps/builder/app/routes/rest.ai._index.ts
@@ -109,6 +109,19 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const requestContext = await createContext(request);
+ if (requestContext.authorization.type !== "user") {
+ return {
+ id: "ai",
+ ...createErrorResponse({
+ error: "unauthorized",
+ status: 401,
+ message: "You don't have edit access to this project",
+ debug: "Unauthorized access attempt",
+ }),
+ llmMessages: [],
+ };
+ }
+
if (requestContext.authorization.userId === undefined) {
return {
id: "ai",
diff --git a/apps/builder/app/routes/rest.ai.detect.ts b/apps/builder/app/routes/rest.ai.detect.ts
index ffc8648df0..91c4cfee81 100644
--- a/apps/builder/app/routes/rest.ai.detect.ts
+++ b/apps/builder/app/routes/rest.ai.detect.ts
@@ -73,6 +73,19 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const requestContext = await createContext(request);
+ if (requestContext.authorization.type !== "user") {
+ return {
+ id: "ai",
+ ...createErrorResponse({
+ error: "unauthorized",
+ status: 401,
+ message: "You don't have edit access to this project",
+ debug: "Unauthorized access attempt",
+ }),
+ llmMessages: [],
+ };
+ }
+
if (requestContext.authorization.userId === undefined) {
return {
id: "ai",
diff --git a/apps/builder/app/routes/rest.patch.ts b/apps/builder/app/routes/rest.patch.ts
index 9b5798f068..06f8d4feed 100644
--- a/apps/builder/app/routes/rest.patch.ts
+++ b/apps/builder/app/routes/rest.patch.ts
@@ -102,10 +102,11 @@ export const action = async ({
const context = await createContext(request);
- if (
- context.authorization.userId === undefined &&
- context.authorization.authToken === undefined
- ) {
+ if (context.authorization.type === "service") {
+ throw new AuthorizationError("Service calls are not allowed");
+ }
+
+ if (context.authorization.type === "anonymous") {
return {
status: "authorization_error",
errors:
diff --git a/apps/builder/app/services/auth.server.utils.ts b/apps/builder/app/services/auth.server.utils.ts
index f2fac74756..a79b0cfe3b 100644
--- a/apps/builder/app/services/auth.server.utils.ts
+++ b/apps/builder/app/services/auth.server.utils.ts
@@ -14,5 +14,5 @@ export const getSessionCookieNameVersion = () => {
// IMPORTANT: Change version in the SaaS platform as well!
// IMPORTANT: Changing the version will cause all users to be logged out.
- return "2";
+ return "3";
};
diff --git a/apps/builder/app/services/bloom-filter.server.test.ts b/apps/builder/app/services/bloom-filter.server.test.ts
index 2baa8c9da4..dc400a7db1 100644
--- a/apps/builder/app/services/bloom-filter.server.test.ts
+++ b/apps/builder/app/services/bloom-filter.server.test.ts
@@ -13,41 +13,41 @@ describe("BloomFilter add/has", () => {
expect(bloomFilter.bitArray.length).toBeGreaterThan(0);
});
- test("should add an item and check its existence", async () => {
+ test("should add an item and check its existence", () => {
const item = "test-item";
- await bloomFilter.add(item);
- const hasItem = await bloomFilter.has(item);
+ bloomFilter.add(item);
+ const hasItem = bloomFilter.has(item);
expect(hasItem).toBe(true);
});
- test("should return false for non-existent items", async () => {
+ test("should return false for non-existent items", () => {
const item = "non-existent-item";
- const hasItem = await bloomFilter.has(item);
+ const hasItem = bloomFilter.has(item);
expect(hasItem).toBe(false);
});
- test("should handle adding the same item multiple times", async () => {
+ test("should handle adding the same item multiple times", () => {
const item = "duplicate-item";
- await bloomFilter.add(item);
- await bloomFilter.add(item);
- const hasItem = await bloomFilter.has(item);
+ bloomFilter.add(item);
+ bloomFilter.add(item);
+ const hasItem = bloomFilter.has(item);
expect(hasItem).toBe(true);
});
- test("should handle multiple items", async () => {
+ test("should handle multiple items", () => {
const items = ["item1", "item2", "item3"];
for (const item of items) {
- await bloomFilter.add(item);
+ bloomFilter.add(item);
}
for (const item of items) {
- const hasItem = await bloomFilter.has(item);
+ const hasItem = bloomFilter.has(item);
expect(hasItem).toBe(true);
}
const notExistedItems = ["na-item1", "na-item2", "na-item3"];
for (const item of notExistedItems) {
- const hasItem = await bloomFilter.has(item);
+ const hasItem = bloomFilter.has(item);
expect(hasItem).toBe(false);
}
});
@@ -60,11 +60,11 @@ describe("BloomFilter serialize/deserialize", () => {
bloomFilter = new BloomFilter(100, 0.01);
});
- test("should serialize and deserialize correctly", async () => {
+ test("should serialize and deserialize correctly", () => {
const items = ["item1", "item2", "item3", "item4", "item5"];
for (const item of items) {
- await bloomFilter.add(item);
+ bloomFilter.add(item);
}
const serialized = bloomFilter.serialize();
@@ -76,45 +76,33 @@ describe("BloomFilter serialize/deserialize", () => {
});
describe("BloomFilter size", () => {
- test("should fail if out of params", async () => {
- expect(() => {
- new BloomFilter(1000, 0.00001);
- }).toThrowError("numHashes is too large");
-
- expect(() => {
- new BloomFilter(100000, 0.01);
- }).toThrowError(
- "Invariant failed: bitSize=958506 is too large, hash is 16-bit"
- );
- });
-
- test("Visual test bloom filter size", async () => {
+ test("Visual test bloom filter size", () => {
const bloomFilter = new BloomFilter(100, 0.02);
for (let i = 0; i < 20; i++) {
- await bloomFilter.add(i.toString());
+ bloomFilter.add(i.toString());
}
const serialized = bloomFilter.serialize();
expect(serialized).toMatchInlineSnapshot(
- `"CAAQAQGCIIBVggEAADBCwABIFEAAAAAABGAAQCJoBEAAABAAAAgCACCAAIQEhIQ0gACAAAgIQAggAgUgEAAAgBETgAAQAECBFEUkAAMqRoIBkREQQMAAEEgIAFAAAACAAAGICAgGBg"`
+ `"AAABKACCAIQICCAAFFIAEUAEKANBBoAJEAGAAAGAgIgAAIGCAIwCAABBIAgEgBBAAIAAUEAAQRAAiCAAEgAAEggAEkMgEAECAAjAAABighAAgEoAEEDEJGAgQAABATgIAEAQCAAQBg"`
);
});
- test("Visual test bloom filter size", async () => {
+ test("Visual test bloom filter size", () => {
const bloomFilter = new BloomFilter(50, 0.02);
for (let i = 0; i < 20; i++) {
- await bloomFilter.add(i.toString());
+ bloomFilter.add(i.toString());
}
const serialized = bloomFilter.serialize();
expect(serialized).toMatchInlineSnapshot(
- `"CAgYQQmiIoV1kgEAgDFTwABYFECBFEUkBGMqRqJplVEQQNAAEEgKAHCAAISEhIW8iAiGBg"`
+ `"UEABaRCCiKQIGiAAFloAE0MkOANDBojJEAHighGAgMoAEMHGJOwiQABBITgMgFBQCIAQBg"`
);
});
});
describe("real life test", () => {
- test.each([50, 100])("should work with real life data", async (maxItems) => {
+ test.each([50, 100])("should work with real life data", (maxItems) => {
const falsePositiveProbability = 0.02;
const bloomFilter = new BloomFilter(maxItems, falsePositiveProbability);
@@ -124,11 +112,11 @@ describe("real life test", () => {
crypto.randomUUID()
);
for (const uuid of uuids) {
- await bloomFilter.add(uuid);
+ bloomFilter.add(uuid);
}
for (const uuid of uuids) {
- expect(await bloomFilter.has(uuid)).toBe(true);
+ expect(bloomFilter.has(uuid)).toBe(true);
}
let falsePositives = 0;
@@ -140,21 +128,23 @@ describe("real life test", () => {
);
for (const uuid of notInSetUuid) {
- const isInSet = await bloomFilter.has(uuid);
+ const isInSet = bloomFilter.has(uuid);
falsePositives += isInSet ? 1 : 0;
}
- expect(falsePositives).toBeLessThan(
- notInSetCount * falsePositiveProbability
- );
-
/*
// Uncomment to play with parameters
console.info(
"False positives",
falsePositives,
+ "of",
+ notInSetUuid.length,
bloomFilter.serialize().length
);
*/
+
+ expect(falsePositives).toBeLessThan(
+ notInSetCount * falsePositiveProbability
+ );
});
});
diff --git a/apps/builder/app/services/bloom-filter.server.ts b/apps/builder/app/services/bloom-filter.server.ts
index 64aa42f395..18e79e7acf 100644
--- a/apps/builder/app/services/bloom-filter.server.ts
+++ b/apps/builder/app/services/bloom-filter.server.ts
@@ -1,13 +1,14 @@
-import invariant from "tiny-invariant";
+const fnv1a = (input: string): number => {
+ const prime = 0x01000193;
+ let hash = 0x811c9dc5;
-const hash = async (input: string) => {
- const encoder = new TextEncoder();
- const data = encoder.encode(input);
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
- return hashBuffer;
-};
+ for (let i = 0; i < input.length; i++) {
+ hash ^= input.charCodeAt(i);
+ hash = Math.imul(hash, prime);
+ }
-const SHA_SIZE = 32;
+ return hash >>> 0; // Convert to 32-bit unsigned integer
+};
const getBit = (arr: Uint8Array, i: number) => (arr[i >> 3] >> (i & 7)) & 1;
@@ -33,23 +34,13 @@ export class BloomFilter {
this.numHashes = Math.round((bitSize / maxItems) * Math.log(2));
- invariant(
- SHA_SIZE >= this.numHashes * 2,
- "numHashes is too large, we are using SHA-256"
- );
-
- invariant(
- bitSize < 0xffff,
- `bitSize=${bitSize} is too large, hash is 16-bit`
- );
-
const size = Math.ceil(bitSize / 8);
this.bitArray = new Uint8Array(size);
}
- async add(item: string) {
- const hashes = await this.#getHashes(item);
+ add(item: string) {
+ const hashes = this.#getHashes(item);
const size = this.bitArray.length * 8;
for (const hash of hashes) {
@@ -57,25 +48,19 @@ export class BloomFilter {
}
}
- async has(item: string) {
- const hashes = await this.#getHashes(item);
+ has(item: string) {
+ const hashes = this.#getHashes(item);
const size = this.bitArray.length * 8;
return hashes.every((hash) => getBit(this.bitArray, hash % size) === 1);
}
- async #getHashes(item: string): Promise<number[]> {
+ #getHashes(item: string): number[] {
const hashes: number[] = [];
- const hashBuffer = await hash(item);
- const hashView = new DataView(hashBuffer);
-
- invariant(
- hashBuffer.byteLength > this.numHashes * 2,
- "numHashes is too large"
- );
-
+ let value = item;
for (let i = 0; i < this.numHashes; i++) {
- const hashValue = hashView.getUint16(i * 2, true);
+ const hashValue = fnv1a(value);
+ value = hashValue.toString();
hashes.push(hashValue);
}
diff --git a/apps/builder/app/services/logout-router.server.ts b/apps/builder/app/services/logout-router.server.ts
index 79974f3a37..3b95f12306 100644
--- a/apps/builder/app/services/logout-router.server.ts
+++ b/apps/builder/app/services/logout-router.server.ts
@@ -4,7 +4,6 @@ import {
procedure,
createCallerFactory,
} from "@webstudio-is/trpc-interface/index.server";
-import invariant from "tiny-invariant";
const dashboardProjectCaller = createCallerFactory(dashboardProjectRouter);
@@ -14,12 +13,11 @@ export const logoutRouter = router({
* Therefore, instead of returning builder app endpoints, we are using projectIds.
*/
getLoggedInProjectIds: procedure.query(async ({ ctx }) => {
- const { isLoggedInToBuilder } = ctx.authorization;
+ if (ctx.authorization.type !== "user") {
+ return [];
+ }
- invariant(
- isLoggedInToBuilder !== undefined,
- "isLoggedInToBuilder is not defined, check the context"
- );
+ const { isLoggedInToBuilder } = ctx.authorization;
const projectIds =
await dashboardProjectCaller(ctx).findCurrentUserProjectIds();
diff --git a/apps/builder/app/shared/clone-project.tsx b/apps/builder/app/shared/clone-project.tsx
index 848c16a989..2d2ccd48d2 100644
--- a/apps/builder/app/shared/clone-project.tsx
+++ b/apps/builder/app/shared/clone-project.tsx
@@ -12,22 +12,25 @@ import {
DialogClose,
Dialog,
DialogActions,
+ toast,
} from "@webstudio-is/design-system";
import { Title, Project } from "@webstudio-is/project";
-import { builderUrl } from "~/shared/router-utils";
-import { trpcClient } from "./trpc/trpc-client";
+import { nativeClient } from "./trpc/trpc-client";
+import { useEffectEvent } from "./hook-utils/effect-event";
const useCloneProject = ({
projectId,
- onOpenChange,
+ onCreate,
+ authToken,
}: {
projectId: Project["id"];
- onOpenChange: (isOpen: boolean) => void;
+ authToken?: string;
+ onCreate: (projectId: Project["id"]) => void;
}) => {
- const { send, state } = trpcClient.project.clone.useMutation();
+ const [state, setState] = useState<"idle" | "loading" | "submitting">("idle");
const [errors, setErrors] = useState<string>();
- const handleSubmit = ({ title }: { title: string }) => {
+ const handleSubmit = async ({ title }: { title: string }) => {
const parsed = Title.safeParse(title);
const errors =
"error" in parsed
@@ -37,16 +40,22 @@ const useCloneProject = ({
setErrors(errors);
if (parsed.success) {
- send({ projectId, title }, (data) => {
- if (data?.id) {
- window.location.href = builderUrl({
- origin: window.origin,
- projectId: data.id,
- });
+ try {
+ setState("submitting");
+
+ const data = await nativeClient.project.clone.mutate({
+ projectId,
+ title,
+ authToken,
+ });
- onOpenChange(false);
- }
- });
+ setState("idle");
+
+ onCreate(data.id);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Unknown error");
+ setState("idle");
+ }
}
};
@@ -125,14 +134,24 @@ export const CloneProjectDialog = ({
isOpen,
project: { id, title },
onOpenChange,
+ authToken,
+ onCreate,
}: {
isOpen: boolean;
- project: Project;
+ project: Pick<Project, "id" | "title">;
+ authToken?: string;
onOpenChange: (isOpen: boolean) => void;
+ onCreate: (projectId: Project["id"]) => void;
}) => {
+ const handleOnCreate = useEffectEvent((projectId: Project["id"]) => {
+ onCreate(projectId);
+ onOpenChange(false);
+ });
+
const { handleSubmit, errors, state } = useCloneProject({
projectId: id,
- onOpenChange,
+ authToken,
+ onCreate: handleOnCreate,
});
return (
diff --git a/apps/builder/app/shared/context.server.ts b/apps/builder/app/shared/context.server.ts
index 657fcaf07c..5c5dfb5086 100644
--- a/apps/builder/app/shared/context.server.ts
+++ b/apps/builder/app/shared/context.server.ts
@@ -11,7 +11,7 @@ import { prisma } from "@webstudio-is/prisma-client";
import { builderAuthenticator } from "~/services/builder-auth.server";
import { readLoginSessionBloomFilter } from "~/services/session.server";
import type { BloomFilter } from "~/services/bloom-filter.server";
-import { isBuilder, isCanvas, isDashboard } from "./router-utils";
+import { isBuilder, isCanvas } from "./router-utils";
import { parseBuilderUrl } from "@webstudio-is/http-client";
export const extractAuthFromRequest = async (request: Request) => {
@@ -40,81 +40,88 @@ export const extractAuthFromRequest = async (request: Request) => {
};
};
+const createTokenAuthorizationContext = async (authToken: string) => {
+ const projectOwnerIdByToken = await prisma.authorizationToken.findUnique({
+ where: {
+ token: authToken,
+ },
+ select: {
+ project: {
+ select: {
+ id: true,
+ userId: true,
+ },
+ },
+ },
+ });
+
+ if (projectOwnerIdByToken === null) {
+ throw new Error(`Project owner can't be found for token ${authToken}`);
+ }
+
+ const ownerId = projectOwnerIdByToken.project.userId;
+ if (ownerId === null) {
+ throw new Error(
+ `Project ${projectOwnerIdByToken.project.id} has null userId`
+ );
+ }
+
+ return {
+ type: "token" as const,
+ authToken,
+ ownerId,
+ };
+};
+
const createAuthorizationContext = async (
request: Request
): Promise<AppContext["authorization"]> => {
- if (isCanvas(request)) {
- throw new Error("Canvas requests can't have authorization context");
- }
-
const { authToken, isServiceCall, sessionData } =
await extractAuthFromRequest(request);
- let ownerId = sessionData?.userId;
+ if (isServiceCall) {
+ return {
+ type: "service",
+ isServiceCall: true,
+ };
+ }
if (authToken != null) {
- const projectOwnerIdByToken = await prisma.authorizationToken.findUnique({
- where: {
- token: authToken,
- },
- select: {
- project: {
- select: {
- id: true,
- userId: true,
- },
- },
- },
- });
-
- if (projectOwnerIdByToken === null) {
- throw new Error(`Project owner can't be found for token ${authToken}`);
- }
-
- const projectOwnerId = projectOwnerIdByToken.project.userId;
- if (projectOwnerId === null) {
- throw new Error(
- `Project ${projectOwnerIdByToken.project.id} has null userId`
- );
- }
- ownerId = projectOwnerId;
+ return await createTokenAuthorizationContext(authToken);
}
- let loginBloomFilter: BloomFilter | undefined = undefined;
- let isLoggedInToBuilder:
- | AppContext["authorization"]["isLoggedInToBuilder"]
- | undefined = undefined;
+ if (sessionData?.userId != null) {
+ const userId = sessionData.userId;
+
+ let loginBloomFilter: BloomFilter | undefined = undefined;
- if (isDashboard(request) && sessionData?.userId !== undefined) {
- isLoggedInToBuilder = async (projectId: string) => {
+ let isLoggedInToBuilder = async (projectId: string) => {
if (loginBloomFilter === undefined) {
loginBloomFilter = await readLoginSessionBloomFilter(request);
}
- return await loginBloomFilter.has(projectId);
+ return loginBloomFilter.has(projectId);
};
- }
- if (isBuilder(request) && sessionData?.userId !== undefined) {
- isLoggedInToBuilder = async (projectId: string) => {
- const parsedUrl = parseBuilderUrl(request.url);
- return parsedUrl.projectId === projectId;
+ if (isBuilder(request)) {
+ isLoggedInToBuilder = async (projectId: string) => {
+ const parsedUrl = parseBuilderUrl(request.url);
+ return parsedUrl.projectId === projectId;
+ };
+ }
+
+ return {
+ type: "user",
+ userId,
+ sessionCreatedAt: sessionData.createdAt,
+ isLoggedInToBuilder,
};
}
- const context: AppContext["authorization"] = {
- userId: sessionData?.userId,
- sessionCreatedAt: sessionData?.createdAt,
- authToken,
- isServiceCall,
- ownerId,
- isLoggedInToBuilder,
- };
-
- return context;
+ return { type: "anonymous" };
};
-const createDomainContext = (_request: Request) => {
+const createDomainContext = () => {
const context: AppContext["domain"] = {
domainTrpc: trpcSharedClient.domain,
};
@@ -128,11 +135,11 @@ const getRequestOrigin = (urlStr: string) => {
return url.origin;
};
-const createDeploymentContext = (request: Request) => {
+const createDeploymentContext = (builderOrigin: string) => {
const context: AppContext["deployment"] = {
deploymentTrpc: trpcSharedClient.deployment,
env: {
- BUILDER_ORIGIN: `${getRequestOrigin(request.url)}`,
+ BUILDER_ORIGIN: getRequestOrigin(builderOrigin),
GITHUB_REF_NAME: staticEnv.GITHUB_REF_NAME ?? "undefined",
GITHUB_SHA: staticEnv.GITHUB_SHA ?? undefined,
},
@@ -150,9 +157,14 @@ const createEntriContext = () => {
const createUserPlanContext = async (
authorization: AppContext["authorization"]
) => {
- const planFeatures = authorization.ownerId
- ? await getUserPlanFeatures(authorization.ownerId)
- : undefined;
+ const ownerId =
+ authorization.type === "token"
+ ? authorization.ownerId
+ : authorization.type === "user"
+ ? authorization.userId
+ : undefined;
+
+ const planFeatures = ownerId ? await getUserPlanFeatures(ownerId) : undefined;
return planFeatures;
};
@@ -183,13 +195,29 @@ export const createPostrestContext = () => {
export const createContext = async (request: Request): Promise<AppContext> => {
const authorization = await createAuthorizationContext(request);
- const domain = createDomainContext(request);
- const deployment = createDeploymentContext(request);
+ const domain = createDomainContext();
+ const deployment = createDeploymentContext(getRequestOrigin(request.url));
const entri = createEntriContext();
const userPlanFeatures = await createUserPlanContext(authorization);
const trpcCache = createTrpcCache();
const postgrest = createPostrestContext();
+ const createTokenContext = async (authToken: string) => {
+ const authorization = await createTokenAuthorizationContext(authToken);
+ const userPlanFeatures = await createUserPlanContext(authorization);
+
+ return {
+ authorization,
+ domain,
+ deployment,
+ entri,
+ userPlanFeatures,
+ trpcCache,
+ postgrest,
+ createTokenContext,
+ };
+ };
+
return {
authorization,
domain,
@@ -198,5 +226,6 @@ export const createContext = async (request: Request): Promise<AppContext> => {
userPlanFeatures,
trpcCache,
postgrest,
+ createTokenContext,
};
};
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index b3fd6630d0..1648bcaae7 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -32,6 +32,7 @@ import {
$uploadingFilesDataStore,
$memoryProps,
$isPreviewMode,
+ $authToken,
} from "./misc";
import { $selectedPage, $pages } from "./pages";
import type { InstanceSelector } from "../tree-utils";
@@ -642,9 +643,15 @@ export const $areResourcesLoading = computed(
const loadResources = async (resourceRequests: ResourceRequest[]) => {
$resourcesLoadingCount.set($resourcesLoadingCount.get() + 1);
+ const authToken = $authToken.get();
+ const headers = new Headers();
+ if (authToken !== undefined) {
+ headers.set("x-auth-token", authToken);
+ }
const response = await fetch(restResourcesLoader(), {
method: "POST",
body: JSON.stringify(resourceRequests),
+ headers,
});
$resourcesLoadingCount.set($resourcesLoadingCount.get() - 1);
if (response.ok === false) {
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index 1b072c375f..1295a66442 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -74,6 +74,18 @@ export const dashboardUrl = (props: { origin: string }) => {
return `${authServerOrigin}/dashboard`;
};
+export const cloneProjectUrl = (props: {
+ origin: string;
+ sourceAuthToken: string;
+}) => {
+ const authServerOrigin = getAuthorizationServerOrigin(props.origin);
+
+ const searchParams = new URLSearchParams();
+ searchParams.set("projectToCloneAuthToken", props.sourceAuthToken);
+
+ return `${authServerOrigin}/dashboard?${searchParams.toString()}`;
+};
+
export const builderDomainsPath = (method: string) => {
const authToken = $authToken.get();
const urlSearchParams = new URLSearchParams();
diff --git a/packages/authorization-token/src/db/authorization-token.ts b/packages/authorization-token/src/db/authorization-token.ts
index 927bb27dc8..300f2dcaad 100644
--- a/packages/authorization-token/src/db/authorization-token.ts
+++ b/packages/authorization-token/src/db/authorization-token.ts
@@ -8,6 +8,20 @@ import {
type AuthorizationToken =
Database["public"]["Tables"]["AuthorizationToken"]["Row"];
+const applyTokenPermissions = (
+ token: AuthorizationToken
+): AuthorizationToken => {
+ if (token.relation !== "viewers") {
+ return {
+ ...token,
+ canClone: true,
+ canCopy: true,
+ };
+ }
+
+ return token;
+};
+
export const findMany = async (
props: { projectId: string },
context: AppContext
@@ -35,7 +49,7 @@ export const findMany = async (
throw dbTokens.error;
}
- return dbTokens.data;
+ return dbTokens.data.map(applyTokenPermissions);
};
export const tokenDefaultPermissions = {
@@ -45,33 +59,37 @@ export const tokenDefaultPermissions = {
export type TokenPermissions = typeof tokenDefaultPermissions;
-export const getTokenPermissions = async (
- props: { projectId: string; token: AuthorizationToken["token"] },
+export const getTokenInfo = async (
+ token: AuthorizationToken["token"],
context: AppContext
-): Promise<TokenPermissions> => {
+) => {
const dbToken = await context.postgrest.client
.from("AuthorizationToken")
.select()
- .eq("projectId", props.projectId)
- .eq("token", props.token)
+ .eq("token", token)
.maybeSingle();
+
if (dbToken.error) {
throw dbToken.error;
}
+
if (dbToken.data === null) {
throw new AuthorizationError("Authorization token not found");
}
- switch (dbToken.data.relation) {
- // canClone, canCopy permissions can be applied for viewers only
- case "viewers":
- return {
- canClone: dbToken.data.canClone,
- canCopy: dbToken.data.canCopy,
- };
- default:
- return tokenDefaultPermissions;
- }
+ return applyTokenPermissions(dbToken.data);
+};
+
+export const getTokenPermissions = async (
+ props: { projectId: string; token: AuthorizationToken["token"] },
+ context: AppContext
+): Promise<TokenPermissions> => {
+ const dbToken = await getTokenInfo(props.token, context);
+
+ return {
+ canClone: dbToken.canClone,
+ canCopy: dbToken.canCopy,
+ };
};
export const create = async (
diff --git a/packages/dashboard/src/db/projects.ts b/packages/dashboard/src/db/projects.ts
index a3a24be6c2..35350e3afb 100644
--- a/packages/dashboard/src/db/projects.ts
+++ b/packages/dashboard/src/db/projects.ts
@@ -6,6 +6,12 @@ import {
import type { DashboardProjects } from "./schema";
export const findMany = async (userId: string, context: AppContext) => {
+ if (context.authorization.type !== "user") {
+ throw new AuthorizationError(
+ "Only logged in users can view the project list"
+ );
+ }
+
if (userId !== context.authorization.userId) {
throw new AuthorizationError(
"Only the project owner can view the project list"
diff --git a/packages/design-system/src/components/dropdown-menu.tsx b/packages/design-system/src/components/dropdown-menu.tsx
index 938daf7999..0ed62851d3 100644
--- a/packages/design-system/src/components/dropdown-menu.tsx
+++ b/packages/design-system/src/components/dropdown-menu.tsx
@@ -52,16 +52,26 @@ export const StyledMenuItem = styled(DropdownMenuPrimitive.Item, menuItemCss, {
export const DropdownMenuItem = forwardRef<
ElementRef<typeof StyledMenuItem>,
ComponentProps<typeof StyledMenuItem> & { icon?: ReactNode }
->(({ icon, children, withIndicator, ...props }, forwardedRef) => (
- <StyledMenuItem
- withIndicator={withIndicator || Boolean(icon)}
- {...props}
- ref={forwardedRef}
- >
- {icon && <div className={menuItemIndicatorCss()}>{icon}</div>}
- {children}
- </StyledMenuItem>
-));
+>(({ icon, children, withIndicator, ...props }, forwardedRef) =>
+ icon ? (
+ <StyledMenuItem
+ withIndicator={withIndicator || Boolean(icon)}
+ {...props}
+ ref={forwardedRef}
+ >
+ <div className={menuItemIndicatorCss()}>{icon}</div>
+ {children}
+ </StyledMenuItem>
+ ) : (
+ <StyledMenuItem
+ withIndicator={withIndicator || Boolean(icon)}
+ {...props}
+ ref={forwardedRef}
+ >
+ {children}
+ </StyledMenuItem>
+ )
+);
DropdownMenuItem.displayName = "DropdownMenuItem";
export const DropdownMenuItemRightSlot = styled("span", {
diff --git a/packages/design-system/src/components/toast.tsx b/packages/design-system/src/components/toast.tsx
index 352af45b9d..5151795cc3 100644
--- a/packages/design-system/src/components/toast.tsx
+++ b/packages/design-system/src/components/toast.tsx
@@ -46,6 +46,7 @@ const StyledViewport = styled(ToastPrimitive.Viewport, {
maxWidth: "100vw",
margin: 0,
listStyle: "none",
+ zIndex: theme.zIndices.max,
outline: "none",
});
diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.ts
index 32abdb9918..54e045f89f 100644
--- a/packages/design-system/src/index.ts
+++ b/packages/design-system/src/index.ts
@@ -23,6 +23,7 @@ export {
MenuItemButton,
MenuCheckedIcon,
MenuItemIndicator,
+ menuItemCss,
} from "./components/menu";
export * from "./components/switch";
export * from "./components/toolbar";
diff --git a/packages/domain/src/trpc/domain.ts b/packages/domain/src/trpc/domain.ts
index 9f7b450749..596b642409 100644
--- a/packages/domain/src/trpc/domain.ts
+++ b/packages/domain/src/trpc/domain.ts
@@ -114,6 +114,10 @@ export const domainRouter = router({
console.info("input.destination", input.destination);
+ if (env.BUILDER_ORIGIN === undefined) {
+ throw new Error("Missing env.BUILDER_ORIGIN");
+ }
+
const result = await deploymentTrpc.publish.mutate({
// used to load build data from the builder see routes/rest.build.$buildId.ts
builderOrigin: env.BUILDER_ORIGIN,
@@ -267,10 +271,19 @@ export const domainRouter = router({
countTotalDomains: procedure.query(async ({ ctx }) => {
try {
- if (ctx.authorization.ownerId === undefined) {
+ if (
+ ctx.authorization.type !== "user" &&
+ ctx.authorization.type !== "token"
+ ) {
throw new Error("Not authorized");
}
- const data = await db.countTotalDomains(ctx.authorization.ownerId);
+
+ const ownerId =
+ ctx.authorization.type === "user"
+ ? ctx.authorization.userId
+ : ctx.authorization.ownerId;
+
+ const data = await db.countTotalDomains(ownerId);
return { success: true, data } as const;
} catch (error) {
return {
diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.ts
index 5fe67d2b5b..6bbee0752a 100644
--- a/packages/project/src/db/project.ts
+++ b/packages/project/src/db/project.ts
@@ -13,6 +13,12 @@ export const findProjectIdsByUserId = async (
userId: string,
context: AppContext
) => {
+ if (context.authorization.type !== "user") {
+ throw new AuthorizationError(
+ "Only logged in users can view the project list"
+ );
+ }
+
if (userId !== context.authorization.userId) {
throw new AuthorizationError(
"Only the project owner can view the project list"
@@ -91,6 +97,10 @@ export const create = async (
) => {
Title.parse(title);
+ if (context.authorization.type !== "user") {
+ throw new AuthorizationError("Only logged in users can create a project");
+ }
+
const userId = context.authorization.userId;
if (userId === undefined) {
@@ -217,24 +227,34 @@ export const clone = async (
projectId: string;
title?: string | undefined;
},
- context: AppContext
+ destinationContext: AppContext,
+ sourceContext: AppContext
) => {
- const project = await loadById(projectId, context);
+ const project = await loadById(projectId, sourceContext);
if (project === null) {
throw new Error(`Not found project "${projectId}"`);
}
- const { userId } = context.authorization;
+ if (destinationContext.authorization.type !== "user") {
+ throw new AuthorizationError("Only logged in users can clone a project");
+ }
+
+ const { userId } = destinationContext.authorization;
if (userId === undefined) {
throw new Error("The user must be authenticated to clone the project");
}
- const clonedProject = await context.postgrest.client.rpc("clone_project", {
- project_id: projectId,
- user_id: userId,
- title: title ?? `${project.title} (copy)`,
- domain: generateDomain(project.title),
- });
+ // Should be some mixed context in case of RLS
+ const clonedProject = await destinationContext.postgrest.client.rpc(
+ "clone_project",
+ {
+ project_id: projectId,
+ user_id: userId,
+ title: title ?? `${project.title} (copy)`,
+ domain: generateDomain(project.title),
+ }
+ );
+
if (clonedProject.error) {
throw clonedProject.error;
}
diff --git a/packages/project/src/trpc/project-router.ts b/packages/project/src/trpc/project-router.ts
index 6cdfdf7a5d..4d3c2a9686 100644
--- a/packages/project/src/trpc/project-router.ts
+++ b/packages/project/src/trpc/project-router.ts
@@ -22,9 +22,19 @@ export const projectRouter = router({
return await db.project.markAsDeleted(input.projectId, ctx);
}),
clone: procedure
- .input(z.object({ projectId: z.string(), title: z.optional(z.string()) }))
+ .input(
+ z.object({
+ projectId: z.string(),
+ title: z.optional(z.string()),
+ authToken: z.optional(z.string()),
+ })
+ )
.mutation(async ({ input, ctx }) => {
- return await db.project.clone(input, ctx);
+ const sourceContext = input.authToken
+ ? await ctx.createTokenContext(input.authToken)
+ : ctx;
+
+ return await db.project.clone(input, ctx, sourceContext);
}),
create: procedure
.input(z.object({ title: Title }))
@@ -42,7 +52,7 @@ export const projectRouter = router({
return await db.project.setMarketplaceApprovalStatus(input, ctx);
}),
findCurrentUserProjectIds: procedure.query(async ({ ctx }) => {
- if (ctx.authorization.userId === undefined) {
+ if (ctx.authorization.type !== "user") {
return [];
}
diff --git a/packages/trpc-interface/src/authorize/project.server.ts b/packages/trpc-interface/src/authorize/project.server.ts
index fcf9eedea0..5fcc4be70e 100644
--- a/packages/trpc-interface/src/authorize/project.server.ts
+++ b/packages/trpc-interface/src/authorize/project.server.ts
@@ -173,13 +173,11 @@ export const hasProjectPermit = async (
) => {
const { authorization } = context;
- const authInfo: AuthInfo | undefined = authorization.isServiceCall
- ? { type: "service" }
- : authorization.authToken !== undefined
- ? { type: "token", authToken: authorization.authToken }
- : authorization.userId !== undefined
- ? { type: "user", userId: authorization.userId }
- : undefined;
+ if (authorization.type === "anonymous") {
+ return false;
+ }
+
+ const authInfo: AuthInfo = authorization;
if (authInfo === undefined) {
return false;
diff --git a/packages/trpc-interface/src/context/context.server.ts b/packages/trpc-interface/src/context/context.server.ts
index 3125f9ae08..87ea1915a6 100644
--- a/packages/trpc-interface/src/context/context.server.ts
+++ b/packages/trpc-interface/src/context/context.server.ts
@@ -4,33 +4,41 @@ import type { Client } from "@webstudio-is/postrest/index.server";
/**
* All necessary parameters for Authorization
*/
-type AuthorizationContext = {
- /**
- * userId of the current authenticated user
- */
- userId: string | undefined;
- sessionCreatedAt: number | undefined;
-
- /**
- * token URLSearchParams or hostname
- */
- authToken: string | undefined;
-
- /**
- * In case of authToken, this is the ownerId of the project
- */
- ownerId: string | undefined;
-
- /**
- * Allow service 2 service communications to skip authorization for view calls
- */
- isServiceCall: boolean;
+type AuthorizationContext =
+ | {
+ type: "user";
+ /**
+ * userId of the current authenticated user
+ */
+ userId: string;
+ sessionCreatedAt: number;
+ /**
+ * Has projectId in the tracked sessions
+ */
+ isLoggedInToBuilder: (projectId: string) => Promise<boolean>;
+ }
+ | {
+ type: "token";
+ /**
+ * token URLSearchParams or hostname
+ */
+ authToken: string;
- /**
- * Has projectId in the tracked sessions
- */
- isLoggedInToBuilder: undefined | ((projectId: string) => Promise<boolean>);
-};
+ /**
+ * In case of authToken, this is the ownerId of the project
+ */
+ ownerId: string;
+ }
+ | {
+ type: "service";
+ /**
+ * Allow service 2 service communications to skip authorization for view calls
+ */
+ isServiceCall: boolean;
+ }
+ | {
+ type: "anonymous";
+ };
type DomainContext = {
domainTrpc: TrpcInterfaceClient["domain"];
@@ -97,4 +105,5 @@ export type AppContext = {
userPlanFeatures: UserPlanFeatures | undefined;
trpcCache: TrpcCache;
postgrest: PostgrestContext;
+ createTokenContext: (token: string) => Promise<AppContext>;
};