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.

chore: Project login (#3990)

Ivan Starkov0b0707e61f8e
diff --git a/.github/actions/vercel/action.yaml b/.github/actions/vercel/action.yaml
index 715cc95c72..3c8972711c 100644
--- a/.github/actions/vercel/action.yaml
+++ b/.github/actions/vercel/action.yaml
@@ -79,6 +79,27 @@ runs:
vercel build
shell: bash
+ - name: Patch
+ run: |
+ # When we deploy on Vercel, it generates a URL like webstudio-saas-mahqcavgo-getwebstudio.vercel.app.
+ # We use the alias oauth-wstd-00-staging.vercel.app for routing, which maps to oauth.staging.webstudio.is on the worker.
+ # Issue: Vercel proxies also set x-forwarded-host, which overrides our header.
+ # We are adding x-forwarded-ws-host on the worker as a workaround, but issues with request.url persist.
+ # Remix and the Vercel adapter lack support for header selection https://github.com/vercel/vercel/blob/9d4d4b6deb6294506016106f78e71f1984adcc7f/packages/remix/defaults/server-node.mjs#L44
+ # Patching server-node.mjs directly without installing Vercel CLI was unsuccessful, so we are using string replacement instead.
+
+ mapfile -t matching_files < <(grep -rl "req\.headers\['x-forwarded-host'\] || req\.headers\.host" "./apps/builder/build")
+ if [ ${#matching_files[@]} -eq 0 ]; then
+ echo "No files found containing the specified string."
+ exit 1
+ fi
+
+ echo "Files containing 'req.headers['x-forwarded-host'] || req.headers.host':"
+ printf '%s\n' "${matching_files[@]}"
+
+ find ./apps/builder/build -type f -exec sed -i "s/req\.headers\['x-forwarded-host'\] || req\.headers\.host/req.headers['x-forwarded-ws-host'] || req.headers['x-forwarded-host'] || req.headers.host/g" {} +
+ shell: bash
+
- name: Deploy
id: deploy
run: |
diff --git a/apps/builder/app/env/env.server.ts b/apps/builder/app/env/env.server.ts
index 0cf3576386..6891f564ad 100644
--- a/apps/builder/app/env/env.server.ts
+++ b/apps/builder/app/env/env.server.ts
@@ -103,6 +103,10 @@ const env = {
SECURE_COOKIE:
process.env.SSL === "true" || process.env.NODE_ENV === "production",
+
+ // Used for project oauth login flow @todo remove ??
+ AUTH_WS_CLIENT_ID: process.env.AUTH_WS_CLIENT_ID ?? "12345",
+ AUTH_WS_CLIENT_SECRET: process.env.AUTH_WS_CLIENT_SECRET ?? "12345678",
};
export type ServerEnv = typeof env;
diff --git a/apps/builder/app/routes/_ui.error.tsx b/apps/builder/app/routes/_ui.error.tsx
new file mode 100644
index 0000000000..0235f264ca
--- /dev/null
+++ b/apps/builder/app/routes/_ui.error.tsx
@@ -0,0 +1,71 @@
+import { type LoaderFunctionArgs, json } from "@remix-run/server-runtime";
+import { useLoaderData } from "@remix-run/react";
+import {
+ getAuthorizationServerOrigin,
+ isBuilderUrl,
+} from "~/shared/router-utils/origins";
+import { builderSessionStorage } from "~/services/builder-session.server";
+import { sessionStorage } from "~/services/session.server";
+import { authenticator } from "~/services/auth.server";
+import { builderAuthenticator } from "~/services/builder-auth.server";
+import { z } from "zod";
+import { fromError } from "zod-validation-error";
+import { lazy } from "react";
+import { ClientOnly } from "~/shared/client-only";
+
+const SessionError = z.object({
+ message: z.string(),
+ description: z.string().optional(),
+});
+
+export const loader = async ({ request }: LoaderFunctionArgs) => {
+ const storage = isBuilderUrl(request.url)
+ ? builderSessionStorage
+ : sessionStorage;
+ const sessionErrorKey = isBuilderUrl(request.url)
+ ? builderAuthenticator.sessionErrorKey
+ : authenticator.sessionErrorKey;
+
+ const session = await storage.getSession(request.headers.get("Cookie"));
+
+ const rawError = session.get(sessionErrorKey);
+
+ const parsedError = SessionError.safeParse(rawError);
+
+ const error = parsedError.success
+ ? parsedError.data
+ : {
+ message: "Unknown error",
+ description: fromError(parsedError.error).toString(),
+ };
+
+ return json(
+ { error, origin: getAuthorizationServerOrigin(request.url) },
+ // remove flash message from session
+ {
+ headers: {
+ "Set-Cookie": await storage.commitSession(session),
+ },
+ }
+ );
+};
+
+const ErrorPage = lazy(async () => {
+ const { ErrorPage } = await import("~/shared/error/error-page.client");
+ return { default: ErrorPage };
+});
+
+/**
+ * @todo Implement the error page
+ */
+const Error = () => {
+ const data = useLoaderData<typeof loader>();
+
+ return (
+ <ClientOnly>
+ <ErrorPage error={data.error} onCloseNavigateTo={data.origin} />
+ </ClientOnly>
+ );
+};
+
+export default Error;
diff --git a/apps/builder/app/routes/_ui.login._index.tsx b/apps/builder/app/routes/_ui.login._index.tsx
index 5eeab51677..473f6fcebb 100644
--- a/apps/builder/app/routes/_ui.login._index.tsx
+++ b/apps/builder/app/routes/_ui.login._index.tsx
@@ -26,19 +26,23 @@ export const loader = async ({
const user = await findAuthenticatedUser(request);
const url = new URL(request.url);
- let returnTo = url.searchParams.get("returnTo") ?? dashboardPath();
-
- // Avoid loops
- if (comparePathnames(returnTo, request.url)) {
- returnTo = dashboardPath();
- }
+ let returnTo = url.searchParams.get("returnTo");
if (user) {
+ returnTo = returnTo ?? dashboardPath();
+ // Avoid loops
+ if (comparePathnames(returnTo, request.url)) {
+ returnTo = dashboardPath();
+ }
+
throw redirect(returnTo);
}
const headers = new Headers();
- headers.append("Set-Cookie", await returnToCookie.serialize(returnTo));
+
+ if (returnTo) {
+ headers.append("Set-Cookie", await returnToCookie.serialize(returnTo));
+ }
return json(
{
diff --git a/apps/builder/app/routes/_ui.tmp.login.tsx b/apps/builder/app/routes/_ui.tmp.login.tsx
new file mode 100644
index 0000000000..310f3490f6
--- /dev/null
+++ b/apps/builder/app/routes/_ui.tmp.login.tsx
@@ -0,0 +1,244 @@
+import { type MetaFunction, useLoaderData } from "@remix-run/react";
+import { json, type LoaderFunctionArgs } from "@remix-run/server-runtime";
+import { authenticator } from "~/services/auth.server";
+import { builderAuthenticator } from "~/services/builder-auth.server";
+import { returnToCookie } from "~/services/cookie.server";
+import { createContext } from "~/shared/context.server";
+import {
+ getAuthorizationServerOrigin,
+ isBuilderUrl,
+ parseBuilderUrl,
+} from "~/shared/router-utils/origins";
+import { builderUrlNew } from "~/shared/router-utils/path-utils";
+import { createDebug } from "~/shared/debug";
+import { ClientOnly } from "~/shared/client-only";
+
+const debug = createDebug(import.meta.url);
+
+export const meta: MetaFunction = () => {
+ return [
+ { title: "Temp login page (to delete)" },
+ { name: "description", content: "Temp login page!" },
+ ];
+};
+
+export const loader = async ({ request }: LoaderFunctionArgs) => {
+ debug("request.url", request.url);
+ debug("isBuildUrl", isBuilderUrl(request.url));
+ debug("Headers", [...request.headers.entries()]);
+ debug("Origin", getAuthorizationServerOrigin(request.url));
+
+ const context = await createContext(request);
+
+ const projectData = await context.postgrest.client
+ .from("Project")
+ .select("id")
+ .order("createdAt", { ascending: false })
+ .limit(1)
+ .single();
+ if (projectData.error) {
+ throw new Error(
+ `Failed to fetch project data: ${projectData.error.message}`
+ );
+ }
+
+ const projectId = isBuilderUrl(request.url)
+ ? parseBuilderUrl(request.url).projectId!
+ : process.env.NODE_ENV === "production"
+ ? "264a609f-ce63-4197-a364-68d239c2f56a"
+ : projectData.data.id;
+
+ const user = isBuilderUrl(request.url)
+ ? await builderAuthenticator.isAuthenticated(request)
+ : await authenticator.isAuthenticated(request);
+
+ const headers = new Headers();
+
+ if (isBuilderUrl(request.url)) {
+ debug("Temporary redirect to /tmp/login after login");
+ const returnTo = request.url;
+ headers.append("Set-Cookie", await returnToCookie.serialize(returnTo));
+ }
+
+ return json(
+ {
+ user,
+ projectId,
+ isBuilderUrl: isBuilderUrl(request.url),
+ origin: getAuthorizationServerOrigin(request.url),
+ },
+ { headers }
+ );
+};
+
+const TmpLogin = () => {
+ const data = useLoaderData<typeof loader>();
+
+ const projectUrl = new URL(
+ builderUrlNew({
+ origin: data.origin,
+ projectId: data.projectId,
+ })
+ );
+
+ projectUrl.pathname = "/tmp/login";
+
+ const noAccessProjectUrl = new URL(
+ builderUrlNew({
+ origin: data.origin,
+ projectId: "9ccd9600-de48-4f3f-898b-042e890ae805",
+ })
+ );
+
+ noAccessProjectUrl.pathname = "/tmp/login";
+
+ const fetchAllProjectIdsLoggedInAfterIssueDate = async (
+ _userId: string,
+ _issueDate: number
+ ) => {
+ return [
+ {
+ id: data.projectId,
+ },
+ ];
+ };
+
+ return (
+ <ClientOnly>
+ <div className="font-sans p-4">
+ <h1 className="text-3xl">Welcome {data.user?.email ?? "Anon"}</h1>
+ <ul className="list-disc mt-4 pl-6 space-y-2">
+ {false === data.isBuilderUrl && (
+ <>
+ <li>
+ <a
+ className="text-blue-700 underline visited:text-purple-900"
+ href={projectUrl.href}
+ rel="noreferrer"
+ >
+ Project link
+ </a>
+ </li>
+ {data.user != null && (
+ <li>
+ <a
+ className="text-blue-700 underline visited:text-purple-900"
+ href="#"
+ rel="noreferrer"
+ onClick={async () => {
+ if (data.user == null) {
+ return;
+ }
+
+ const projectsToLogout =
+ await fetchAllProjectIdsLoggedInAfterIssueDate(
+ data.user.id,
+ 0
+ // data.user.sessionIssueDate
+ );
+
+ // @todo use https://github.com/sindresorhus/p-all to execute in parallel like concurrency=5 stopOnError=false
+ // @todo remove /logout from rate limiter
+ for (const project of projectsToLogout) {
+ const logoutProjectUrl = new URL(
+ "/logout",
+ builderUrlNew({
+ origin: data.origin,
+ projectId: project.id,
+ })
+ );
+
+ console.info(`Logout ${logoutProjectUrl.href}`);
+
+ await fetch(logoutProjectUrl.href, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ redirect: "manual",
+ credentials: "include",
+ });
+ }
+ }}
+ >
+ Logout from AllProjects {data.user.email}
+ </a>
+ </li>
+ )}
+
+ <li>
+ <a
+ className="text-blue-700 underline visited:text-purple-900"
+ href={noAccessProjectUrl.href}
+ rel="noreferrer"
+ >
+ Project link you have no access to
+ </a>
+ </li>
+ </>
+ )}
+ {false === data.isBuilderUrl && data.user == null && (
+ <li>
+ <a
+ className="text-blue-700 underline visited:text-purple-900"
+ href={"/login"}
+ rel="noreferrer"
+ >
+ Login at authorizer app
+ </a>
+ </li>
+ )}
+
+ {false === data.isBuilderUrl && data.user != null && (
+ <li>
+ <a
+ className="text-blue-700 underline visited:text-purple-900"
+ href={"/logout"}
+ rel="noreferrer"
+ >
+ Logout at authorizer app
+ </a>
+ </li>
+ )}
+
+ {data.isBuilderUrl && (
+ <>
+ <li>
+ <a
+ className="text-blue-700 underline visited:text-purple-900"
+ href={`${data.origin}/tmp/login`}
+ rel="noreferrer"
+ >
+ Goto Auth Server
+ </a>
+ </li>
+
+ <li>
+ <a
+ className="text-blue-700 underline visited:text-purple-900"
+ href={"/auth/ws"}
+ rel="noreferrer"
+ >
+ Run Project Login
+ </a>
+ </li>
+ {data.user != null && (
+ <li>
+ <a
+ className="text-blue-700 underline visited:text-purple-900"
+ href={"/logout"}
+ rel="noreferrer"
+ >
+ Run Project Logout
+ </a>
+ </li>
+ )}
+ </>
+ )}
+ </ul>
+ </div>
+ </ClientOnly>
+ );
+};
+
+export default TmpLogin;
diff --git a/apps/builder/app/routes/auth.ws.ts b/apps/builder/app/routes/auth.ws.ts
new file mode 100644
index 0000000000..bd4c79daf7
--- /dev/null
+++ b/apps/builder/app/routes/auth.ws.ts
@@ -0,0 +1,37 @@
+import type { LoaderFunction } from "@remix-run/node";
+import { createDebug } from "~/shared/debug";
+import { builderAuthenticator } from "~/services/builder-auth.server";
+import { isBuilderUrl } from "~/shared/router-utils/origins";
+
+const debug = createDebug(import.meta.url);
+
+export const loader: LoaderFunction = async ({ request }) => {
+ try {
+ if (false === isBuilderUrl(request.url)) {
+ debug(`Request url is not the builder URL ${request.url}`);
+
+ return new Response(null, {
+ status: 404,
+ statusText: "Only builder URL is allowed",
+ });
+ }
+
+ debug(
+ "Authenticate request received, starting authentication and authorization process"
+ );
+
+ return await builderAuthenticator.authenticate("ws", request, {
+ throwOnError: true,
+ });
+ } catch (error) {
+ // all redirects are basically errors and in that case we don't want to catch it
+ if (error instanceof Response) {
+ return error;
+ }
+
+ debug("error", error);
+
+ console.error("error", error);
+ throw error;
+ }
+};
diff --git a/apps/builder/app/routes/auth.ws_.callback.ts b/apps/builder/app/routes/auth.ws_.callback.ts
new file mode 100644
index 0000000000..ba98ec3d41
--- /dev/null
+++ b/apps/builder/app/routes/auth.ws_.callback.ts
@@ -0,0 +1,70 @@
+import { type LoaderFunction, redirect } from "@remix-run/server-runtime";
+import { AuthorizationError } from "remix-auth";
+import { createDebug } from "~/shared/debug";
+import { isBuilderUrl } from "~/shared/router-utils/origins";
+import { returnToPath } from "~/services/cookie.server";
+import { builderAuthenticator } from "~/services/builder-auth.server";
+import { OAuth2Error } from "remix-auth-oauth2";
+import { builderSessionStorage } from "~/services/builder-session.server";
+
+const debug = createDebug(import.meta.url);
+
+export const loader: LoaderFunction = async ({ request }) => {
+ try {
+ if (false === isBuilderUrl(request.url)) {
+ debug(`Request url is not the builder URL ${request.url}`);
+
+ return new Response(null, {
+ status: 404,
+ statusText: "Only builder URL is allowed",
+ });
+ }
+
+ const returnTo = await returnToPath(request);
+
+ debug("Start exchanging the code for the access token");
+
+ await builderAuthenticator.authenticate("ws", request, {
+ throwOnError: true,
+ successRedirect: returnTo,
+ });
+ } catch (error) {
+ // all redirects are basically errors and in that case we don't want to catch it
+ if (error instanceof Response) {
+ return error;
+ }
+
+ if (error instanceof AuthorizationError) {
+ debug("Authorization error", error.message, error.cause?.message);
+
+ const sessionError = {
+ message: error.message,
+ description: "",
+ };
+
+ if (error.cause instanceof OAuth2Error) {
+ debug(
+ "OAuth2Error error",
+ error.cause?.message,
+ error.cause?.description
+ );
+ sessionError.description = error.cause.description ?? "";
+ }
+
+ const session = await builderSessionStorage.getSession(
+ request.headers.get("Cookie")
+ );
+ session.flash(builderAuthenticator.sessionErrorKey, sessionError);
+
+ throw redirect("/error", {
+ headers: {
+ "Set-Cookie": await builderSessionStorage.commitSession(session),
+ },
+ });
+ }
+
+ debug("error", error);
+ console.error("error", error);
+ throw error;
+ }
+};
diff --git a/apps/builder/app/routes/logout.tsx b/apps/builder/app/routes/logout.tsx
index 27eb9c0dac..68d81e66c7 100644
--- a/apps/builder/app/routes/logout.tsx
+++ b/apps/builder/app/routes/logout.tsx
@@ -1,11 +1,49 @@
-import type { ActionFunctionArgs } from "@remix-run/server-runtime";
+import { type LoaderFunctionArgs } from "@remix-run/server-runtime";
+import { createDebug } from "~/shared/debug";
import { authenticator } from "~/services/auth.server";
-import { loginPath } from "~/shared/router-utils";
+import { builderAuthenticator } from "~/services/builder-auth.server";
+import {
+ getAuthorizationServerOrigin,
+ isBuilderUrl,
+} from "~/shared/router-utils/origins";
-export default function Logout() {
- return null;
-}
+const debug = createDebug(import.meta.url);
-export const loader = async ({ request }: ActionFunctionArgs) => {
- await authenticator.logout(request, { redirectTo: loginPath({}) });
+export const loader = async ({ request }: LoaderFunctionArgs) => {
+ debug("Logout request received", request.url);
+
+ try {
+ if (isBuilderUrl(request.url)) {
+ debug("Temporary redirect to /tmp/login after logout");
+ await builderAuthenticator.logout(request, {
+ redirectTo: `${getAuthorizationServerOrigin(request.url)}/tmp/login`,
+ });
+ } else {
+ await authenticator.logout(request, { redirectTo: "/" });
+ }
+ } catch (error) {
+ if (error instanceof Response) {
+ const contentType = request.headers.get("Content-Type");
+
+ if (contentType?.includes("application/json")) {
+ const headers = new Headers(error.headers);
+ headers.set("Content-Type", "application/json");
+ return new Response(
+ JSON.stringify({
+ success: true,
+ }),
+ {
+ headers,
+ status: 200,
+ }
+ );
+ }
+
+ return error;
+ }
+
+ throw error;
+ }
+
+ throw new Error("Should not reach this point");
};
diff --git a/apps/builder/app/routes/n8n.$.tsx b/apps/builder/app/routes/n8n.$.tsx
index 826c47b9d8..ba9285f5f6 100644
--- a/apps/builder/app/routes/n8n.$.tsx
+++ b/apps/builder/app/routes/n8n.$.tsx
@@ -57,12 +57,6 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
n8nWebhookUrl.search = new URL(request.url).search;
const requestUrl = new URL(request.url);
- const host =
- request.headers.get("x-forwarded-host") ?? request.headers.get("host");
-
- if (host != null) {
- requestUrl.host = host;
- }
const response = await fetch(n8nWebhookUrl.href, {
method: "POST",
diff --git a/apps/builder/app/routes/oauth.ws.authorize.tsx b/apps/builder/app/routes/oauth.ws.authorize.tsx
new file mode 100644
index 0000000000..eef1b53fd7
--- /dev/null
+++ b/apps/builder/app/routes/oauth.ws.authorize.tsx
@@ -0,0 +1,226 @@
+import { json, redirect, type LoaderFunction } from "@remix-run/server-runtime";
+import { z } from "zod";
+import { createDebug } from "~/shared/debug";
+import { fromError } from "zod-validation-error";
+import { getAuthorizationServerOrigin } from "~/shared/router-utils/origins";
+import env from "~/env/env.server";
+import { authenticator } from "~/services/auth.server";
+import { returnToCookie } from "~/services/cookie.server";
+import { createCodeToken } from "~/services/token.server";
+import { isUserAuthorizedForProject } from "~/services/builder-access.server";
+
+const debug = createDebug(import.meta.url);
+
+// https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1
+const createOauthError =
+ (redirectUri: string, state: string) =>
+ (
+ error: "invalid_request" | "invalid_scope" | "unauthorized_client",
+ errorDescription: string
+ ) => {
+ const url = new URL(redirectUri);
+ url.search = "";
+
+ url.searchParams.set("error", error);
+ url.searchParams.set("error_description", errorDescription);
+ if (state) {
+ url.searchParams.set("state", state);
+ }
+
+ return redirect(url.href, { status: 302 });
+ };
+
+/**
+ * OAuth 2.0 Authorization Request
+ *
+ * https://datatracker.ietf.org/doc/html/rfc7636#section-4.3
+ *
+ * https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1
+ */
+const OAuthParams = z.object({
+ // Ensure that the response_type is valid and supported by the authorization server (e.g., code for the authorization code grant type).
+ response_type: z.literal("code"),
+ redirect_uri: z.string().url(),
+
+ client_id: z.string(),
+ state: z.string(),
+ scope: z
+ .string()
+ .refine((str) => str.startsWith("project:"), {
+ message: "Only 'project:' scopes are allowed",
+ })
+ .transform((scope) => ({
+ projectId: scope.split(":")[1],
+ })),
+ code_challenge: z.string(),
+ code_challenge_method: z.literal("S256"),
+});
+
+const OAuthRedirectUri = z.object({
+ redirect_uri: z.string().url(),
+});
+
+/**
+ * Based RFC 6749 and RFC 7636
+ *
+ * https://datatracker.ietf.org/doc/html/rfc6749
+ *
+ * https://datatracker.ietf.org/doc/html/rfc7636
+ */
+export const loader: LoaderFunction = async ({ request }) => {
+ try {
+ debug("Authorize request received", request.url);
+
+ const url = new URL(request.url);
+ const searchParams = Object.fromEntries(url.searchParams);
+
+ const parsedRedirect = OAuthRedirectUri.safeParse(searchParams);
+
+ if (false === parsedRedirect.success) {
+ debug("redirect_uri not provided in query params");
+
+ return json(
+ {
+ error: "invalid_request",
+ error_description: "No redirect_uri provided",
+ error_uri: "https://tools.ietf.org/html/rfc6749#section-3.1.2",
+ },
+ { status: 400 }
+ );
+ }
+
+ // eslint-disable-next-line camelcase
+ const { redirect_uri } = parsedRedirect.data;
+
+ // Validate the redirect_uri
+ // It is not pre-registered but it must match the AuthorizationServerOrigin
+ if (
+ getAuthorizationServerOrigin(request.url) !==
+ getAuthorizationServerOrigin(redirect_uri)
+ ) {
+ debug("redirect_uri does not match the registered redirect URIs");
+
+ return json(
+ {
+ error: "invalid_request",
+ error_description:
+ "The redirect_uri provided does not match the registered redirect URIs.",
+ error_uri: "https://tools.ietf.org/html/rfc6749#section-3.1.2",
+ },
+ { status: 400 }
+ );
+ }
+
+ let oauthError = createOauthError(redirect_uri, searchParams.state);
+
+ const parsedOAuthParams = OAuthParams.safeParse(searchParams);
+
+ if (false === parsedOAuthParams.success) {
+ debug(fromError(parsedOAuthParams.error).toString());
+
+ return oauthError(
+ "invalid_request",
+ fromError(parsedOAuthParams.error).toString()
+ );
+ }
+
+ // Reinit with parsed state
+ oauthError = createOauthError(redirect_uri, parsedOAuthParams.data.state);
+
+ // client_id: Verify that the client_id is valid and corresponds to a registered client.
+ if (parsedOAuthParams.data.client_id !== env.AUTH_WS_CLIENT_ID) {
+ debug("Client is not registered");
+
+ return oauthError("unauthorized_client", "Client is not registered");
+ }
+
+ const oAuthParams = parsedOAuthParams.data;
+
+ const user = await authenticator.isAuthenticated(request);
+
+ if (user) {
+ debug(`User id=${user.id} is authenticated`);
+
+ const isAuthorized = await isUserAuthorizedForProject(
+ user.id,
+ oAuthParams.scope.projectId
+ );
+
+ // scope: Ensure the requested scope is valid, authorized, and within the permissions granted to the client.
+ if (false === isAuthorized) {
+ debug(
+ `User ${user.id} is not the owner of ${oAuthParams.scope.projectId}, denying access`
+ );
+ return oauthError(
+ "unauthorized_client",
+ "User does not have access to the project"
+ );
+ }
+
+ debug(
+ `User ${user.id} is the owner of ${oAuthParams.scope.projectId}, creating token`
+ );
+
+ // We do not use database now.
+ // https://datatracker.ietf.org/doc/html/rfc7636#section-4.4
+ const code = await createCodeToken(
+ {
+ userId: user.id,
+ projectId: oAuthParams.scope.projectId,
+ codeChallenge: oAuthParams.code_challenge,
+ },
+ env.AUTH_WS_CLIENT_SECRET,
+ { maxAge: 1000 * 60 * 5 }
+ );
+
+ const redirectUri = new URL(oAuthParams.redirect_uri);
+ redirectUri.search = "";
+
+ redirectUri.searchParams.set("code", code);
+ // state: If present, store the state parameter to return it unchanged in the response
+ redirectUri.searchParams.set("state", oAuthParams.state);
+
+ debug(
+ `Code ${code} created, redirecting to redirect_uri: ${redirectUri.href}`
+ );
+
+ return redirect(redirectUri.href);
+ }
+
+ user satisfies null;
+
+ debug(
+ "User is not authenticated, saving current url to returnTo cookie and redirecting to login"
+ );
+
+ const headers = new Headers();
+ // Issue with local development, so force https
+ const returnToUrl = new URL(request.url);
+ returnToUrl.protocol = "https";
+
+ // We don't want to have all params above in the URL, so save in returnTo cookie immediately
+ headers.append(
+ "Set-Cookie",
+ await returnToCookie.serialize(returnToUrl.href)
+ );
+
+ return redirect("/login", { headers });
+ } catch (error) {
+ if (error instanceof Response) {
+ return error;
+ }
+
+ console.error("error", error);
+ debug("error", error);
+
+ throw json(
+ {
+ error: "server_error",
+ error_description:
+ error instanceof Error ? error.message : "Unknown error",
+ error_uri: "",
+ },
+ { status: 500 }
+ );
+ }
+};
diff --git a/apps/builder/app/routes/oauth.ws.token.ts b/apps/builder/app/routes/oauth.ws.token.ts
new file mode 100644
index 0000000000..247651f2f3
--- /dev/null
+++ b/apps/builder/app/routes/oauth.ws.token.ts
@@ -0,0 +1,157 @@
+import { type ActionFunctionArgs, json } from "@remix-run/server-runtime";
+import { z } from "zod";
+
+import { createDebug } from "~/shared/debug";
+import { fromError } from "zod-validation-error";
+import env from "~/env/env.server";
+import {
+ createAccessToken,
+ readAccessToken,
+ readCodeToken,
+ verifyChallenge,
+} from "~/services/token.server";
+import { isUserAuthorizedForProject } from "~/services/builder-access.server";
+
+/**
+ * OAuth 2.0 Token Request
+ *
+ * https://datatracker.ietf.org/doc/html/rfc7636#section-4.5
+ *
+ * https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
+ */
+const TokenRequest = z.object({
+ // Check that the grant_type parameter is present and is one of the supported values
+ grant_type: z.literal("authorization_code"),
+ code: z.string(),
+ redirect_uri: z.string().url(),
+ code_verifier: z.string(),
+ client_id: z.string(),
+ client_secret: z.string(),
+});
+
+const debug = createDebug(import.meta.url);
+
+/**
+ * OAuth 2.0 Token Request
+ *
+ * https://datatracker.ietf.org/doc/html/rfc7636
+ *
+ * https://datatracker.ietf.org/doc/html/rfc6749
+ */
+export const action = async ({ request }: ActionFunctionArgs) => {
+ debug("Token request received");
+ const jsonBody = Object.fromEntries((await request.formData()).entries());
+ debug("Token request received", jsonBody);
+
+ const parsedBody = TokenRequest.safeParse(jsonBody);
+
+ if (false === parsedBody.success) {
+ debug(fromError(parsedBody.error).toString());
+
+ return json(
+ {
+ error: "invalid_request",
+ error_description: fromError(parsedBody.error).toString(),
+ error_uri: "https://tools.ietf.org/html/rfc6749#section-5.2",
+ },
+ { status: 400 }
+ );
+ }
+
+ const body = parsedBody.data;
+
+ // Validate the client’s credentials (e.g., client_id and client_secret) using HTTP Basic Authentication or form-encoded parameters.
+ if (
+ body.client_id !== env.AUTH_WS_CLIENT_ID ||
+ body.client_secret !== env.AUTH_WS_CLIENT_SECRET
+ ) {
+ debug("client_id and client_secret do not match", body.code);
+ return json(
+ {
+ error: "invalid_client",
+ error_description: "invalid client credentials",
+ error_uri: "https://tools.ietf.org/html/rfc6749#section-5.2",
+ },
+ { status: 401 }
+ );
+ }
+
+ // Ensure the code parameter is present and valid.
+ const codeToken = await readCodeToken(body.code, env.AUTH_WS_CLIENT_SECRET);
+
+ if (codeToken === undefined) {
+ debug("Code can not be read", body.code);
+ return json(
+ {
+ error: "invalid_grant",
+ error_description: "invalid code",
+ error_uri: "https://tools.ietf.org/html/rfc6749#section-5.2",
+ },
+ { status: 400 }
+ );
+ }
+
+ // verify the code_verifier against the stored code_challenge
+ const isChallengeVerified = await verifyChallenge(
+ body.code_verifier,
+ codeToken.codeChallenge
+ );
+ if (false === isChallengeVerified) {
+ debug(
+ "Code verifier does not match",
+ body.code_verifier,
+ codeToken.codeChallenge
+ );
+ return json(
+ {
+ error: "invalid_grant",
+ error_description: "invalid code_verifier",
+ error_uri: "https://tools.ietf.org/html/rfc6749#section-5.2",
+ },
+ { status: 400 }
+ );
+ }
+
+ const { projectId, userId } = codeToken;
+
+ const isAuthorized = await isUserAuthorizedForProject(userId, projectId);
+
+ if (false === isAuthorized) {
+ debug("User does not have access to the project", userId, projectId);
+ return json(
+ {
+ error: "invalid_grant",
+ error_description: "user does not have access to the project",
+ error_uri: "https://tools.ietf.org/html/rfc6749#section-5.2",
+ },
+ { status: 400 }
+ );
+ }
+
+ const maxAge = 1000 * 60;
+
+ // Generate a short-lived token, as its sole purpose is to log the user in.
+ const accessToken = await createAccessToken(
+ { userId, projectId },
+ env.AUTH_WS_CLIENT_SECRET,
+ {
+ maxAge,
+ }
+ );
+
+ debug("Token created", accessToken);
+
+ debug(
+ "readAccessToken",
+ await readAccessToken(accessToken, env.AUTH_WS_CLIENT_SECRET)
+ );
+
+ return json(
+ {
+ access_token: accessToken,
+ token_type: "Bearer",
+ expires_in: Date.now() + maxAge,
+ },
+ { status: 200 }
+ );
+};
diff --git a/apps/builder/app/services/auth-strategy/ws.server.ts b/apps/builder/app/services/auth-strategy/ws.server.ts
new file mode 100644
index 0000000000..d67255971e
--- /dev/null
+++ b/apps/builder/app/services/auth-strategy/ws.server.ts
@@ -0,0 +1,75 @@
+import type { StrategyVerifyCallback } from "remix-auth";
+import {
+ OAuth2Strategy,
+ type OAuth2Profile,
+ type OAuth2StrategyOptions,
+ type OAuth2StrategyVerifyParams,
+} from "remix-auth-oauth2";
+import { AsyncLocalStorage } from "node:async_hooks";
+
+type DynamicProps = "authorizationEndpoint" | "tokenEndpoint" | "redirectURI";
+
+export type OAuth2StrategyOptionsOverrides = Partial<OAuth2StrategyOptions> &
+ Pick<OAuth2StrategyOptions, DynamicProps>;
+
+const asyncLocalStorage = new AsyncLocalStorage<
+ Partial<OAuth2StrategyOptions>
+>();
+
+/**
+ * The main issue with OAuth2Strategy is that it forces us to define authorizationEndpoint, tokenEndpoint, and redirectURI
+ * at the time of constructing the instance.
+ * However, in our case, these values are dynamic because we use multiple domains, such as development, staging, and production.
+ * The solution is to wrap the options object with a proxy, retrieving the necessary options from localAsyncStorage and proxying
+ * all requests through asyncLocalStorage.run
+ */
+export class WsStrategy<
+ User,
+ Profile extends OAuth2Profile = { provider: string },
+ ExtraParams extends Record<string, unknown> = Record<string, never>,
+> extends OAuth2Strategy<User, Profile, ExtraParams> {
+ constructor(
+ options: OAuth2StrategyOptions,
+ verify: StrategyVerifyCallback<
+ User,
+ OAuth2StrategyVerifyParams<Profile, ExtraParams>
+ >,
+ overrideOptions: (request: Request) => OAuth2StrategyOptionsOverrides
+ ) {
+ super(options, verify);
+
+ this.options = new Proxy<OAuth2StrategyOptions>(this.options, {
+ get: (target, property, receiver) => {
+ const store = asyncLocalStorage.getStore();
+ return (
+ store?.[property as keyof OAuth2StrategyOptions] ??
+ Reflect.get(target, property, receiver)
+ );
+ },
+ });
+
+ return new Proxy(this, {
+ get: function (target, property, receiver) {
+ const targetProp = target[property as keyof typeof target];
+ if (
+ typeof targetProp === "function" &&
+ // do not wrap if already wrapped
+ asyncLocalStorage.getStore() === undefined
+ ) {
+ return (...args: unknown[]) => {
+ const request = args.find((arg) => arg instanceof Request);
+
+ return asyncLocalStorage.run(
+ request ? overrideOptions(request) : {},
+ () => {
+ return Reflect.apply(targetProp, receiver, args);
+ }
+ );
+ };
+ }
+
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ }
+}
diff --git a/apps/builder/app/services/builder-access.server.ts b/apps/builder/app/services/builder-access.server.ts
new file mode 100644
index 0000000000..62252f3552
--- /dev/null
+++ b/apps/builder/app/services/builder-access.server.ts
@@ -0,0 +1,22 @@
+import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
+import { createPostrestContext } from "~/shared/context.server";
+
+/**
+ * Check if a user is authorized to access a project during the Builder authentication process.
+ */
+export const isUserAuthorizedForProject = async (
+ userId: string,
+ projectId: string
+) => {
+ const postgrestContext = createPostrestContext();
+
+ // Only the project owner can access the Builder URL with authentication credentials (session).
+ const isProjectOwner = await authorizeProject.checkProjectPermit(
+ projectId,
+ "own",
+ { type: "user", userId },
+ postgrestContext.client
+ );
+
+ return isProjectOwner;
+};
diff --git a/apps/builder/app/services/builder-auth.server.ts b/apps/builder/app/services/builder-auth.server.ts
new file mode 100644
index 0000000000..9b0d8e1ea9
--- /dev/null
+++ b/apps/builder/app/services/builder-auth.server.ts
@@ -0,0 +1,93 @@
+import { Authenticator, AuthorizationError } from "remix-auth";
+import { builderSessionStorage } from "./builder-session.server";
+import env from "~/env/env.server";
+
+import {
+ type OAuth2StrategyOptionsOverrides,
+ WsStrategy,
+} from "./auth-strategy/ws.server";
+import {
+ getAuthorizationServerOrigin,
+ getRequestOrigin,
+ parseBuilderUrl,
+} from "~/shared/router-utils/origins";
+import { createDebug } from "~/shared/debug";
+import { readAccessToken } from "./token.server";
+import { getUserById, type User } from "~/shared/db/user.server";
+import { isUserAuthorizedForProject } from "./builder-access.server";
+
+const debug = createDebug(import.meta.url);
+
+export const builderAuthenticator = new Authenticator<User>(
+ builderSessionStorage,
+ {
+ throwOnError: true,
+ }
+);
+
+builderAuthenticator.use(
+ new WsStrategy<User>(
+ {
+ clientId: env.AUTH_WS_CLIENT_ID,
+ clientSecret: env.AUTH_WS_CLIENT_SECRET,
+ authorizationEndpoint: "https://OVERRIDDEN_ENDPOINT/oauth2/authorize",
+ tokenEndpoint: "https://OVERRIDDEN_ENDPOINT/oauth2/token",
+ redirectURI: "https://OVERRIDDEN_ENDPOINT/auth/callback",
+ codeChallengeMethod: "S256",
+ authenticateWith: "request_body",
+ },
+ async ({ tokens, request }) => {
+ const accessToken = await readAccessToken(
+ tokens.access_token,
+ env.AUTH_WS_CLIENT_SECRET
+ );
+
+ if (accessToken === undefined) {
+ debug("Invalid or expired access token", tokens.access_token);
+
+ throw new AuthorizationError("Invalid or expired access token");
+ }
+
+ const { projectId } = parseBuilderUrl(request.url);
+
+ if (accessToken.projectId !== projectId) {
+ throw new AuthorizationError(
+ "Token projectId and request projectId do not match"
+ );
+ }
+
+ const isAuthorized = await isUserAuthorizedForProject(
+ accessToken.userId,
+ projectId
+ );
+
+ // We don't need this check because the token is already verified, anyway let's keep it for now
+ if (false === isAuthorized) {
+ throw new AuthorizationError(
+ "User does not have access to this project"
+ );
+ }
+
+ debug("User authenticated", accessToken.userId);
+
+ return await getUserById(accessToken.userId);
+ },
+ (request: Request): OAuth2StrategyOptionsOverrides => {
+ const origin = getRequestOrigin(request.url);
+ const authOrigin = getAuthorizationServerOrigin(request.url);
+ const { projectId } = parseBuilderUrl(request.url);
+
+ if (origin === authOrigin) {
+ throw new Error("Origin and authOrigin cannot be same");
+ }
+
+ return {
+ authorizationEndpoint: `${authOrigin}/oauth/ws/authorize`,
+ tokenEndpoint: `${authOrigin}/oauth/ws/token`,
+ redirectURI: `${origin}/auth/ws/callback`,
+ scopes: [`project:${projectId}`],
+ };
+ }
+ ),
+ "ws"
+);
diff --git a/apps/builder/app/services/builder-session.server.ts b/apps/builder/app/services/builder-session.server.ts
new file mode 100644
index 0000000000..9e60b5df91
--- /dev/null
+++ b/apps/builder/app/services/builder-session.server.ts
@@ -0,0 +1,13 @@
+import { createCookieSessionStorage } from "@remix-run/node";
+import env from "~/env/env.server";
+
+export const builderSessionStorage = createCookieSessionStorage({
+ cookie: {
+ name: "_builder_session", // use any name you want here
+ sameSite: "lax", // this helps with CSRF
+ path: "/", // remember to add this so the cookie will work in all routes
+ httpOnly: true, // for security reasons, make this cookie http only
+ secrets: env.AUTH_SECRET ? [env.AUTH_SECRET] : undefined, // replace this with an actual secret
+ secure: true,
+ },
+});
diff --git a/apps/builder/app/services/cookie.server.ts b/apps/builder/app/services/cookie.server.ts
index cdeb9c4922..5be6cd789b 100644
--- a/apps/builder/app/services/cookie.server.ts
+++ b/apps/builder/app/services/cookie.server.ts
@@ -6,7 +6,7 @@ export const returnToCookie = createCookie("returnTo", {
path: "/",
httpOnly: true,
sameSite: "lax",
- maxAge: 60, // 1 minute because it makes no sense to keep it for a long time
+ maxAge: 60 * 5, // 5 minutes because it makes no sense to keep it for a long time
secure: env.SECURE_COOKIE,
});
diff --git a/apps/builder/app/services/session.server.ts b/apps/builder/app/services/session.server.ts
index fd5e9e7c27..a9ba821f3c 100644
--- a/apps/builder/app/services/session.server.ts
+++ b/apps/builder/app/services/session.server.ts
@@ -13,6 +13,3 @@ export const sessionStorage = createCookieSessionStorage({
secure: env.SECURE_COOKIE,
},
});
-
-// you can also export the methods individually for your own usage
-export const { getSession, commitSession, destroySession } = sessionStorage;
diff --git a/apps/builder/app/services/token.server.test.ts b/apps/builder/app/services/token.server.test.ts
new file mode 100644
index 0000000000..2fea6f0b00
--- /dev/null
+++ b/apps/builder/app/services/token.server.test.ts
@@ -0,0 +1,42 @@
+import {
+ encrypt,
+ decrypt,
+ createAccessToken,
+ readAccessToken,
+} from "./token.server";
+import { test, expect } from "@jest/globals";
+import { nanoid } from "nanoid";
+
+test.each([
+ "",
+ nanoid(1),
+ nanoid(2),
+ nanoid(5),
+ nanoid(10),
+ nanoid(20),
+ nanoid(30),
+ nanoid(40),
+])("Encrypt and decrypt", async (cithertext) => {
+ const secret =
+ "JDKHSJFHKJHFSKJDHFJSDHFKJHDKJFHSKJDHFKJHFKJSFHKKADHJKSHDJKSHAJKHDASKDJH";
+
+ expect(await decrypt(await encrypt(cithertext, secret), secret)).toBe(
+ cithertext
+ );
+});
+
+test("Access token", async () => {
+ const secret = "1212121212";
+
+ const token = await createAccessToken(
+ { userId: "1", projectId: "2" },
+ secret,
+ {
+ maxAge: 1000 * 60,
+ }
+ );
+
+ const tokenPayload = await readAccessToken(token, secret);
+
+ expect(tokenPayload).toEqual({ userId: "1", projectId: "2" });
+});
diff --git a/apps/builder/app/services/token.server.ts b/apps/builder/app/services/token.server.ts
new file mode 100644
index 0000000000..1729d0729b
--- /dev/null
+++ b/apps/builder/app/services/token.server.ts
@@ -0,0 +1,178 @@
+import jwt from "@tsndr/cloudflare-worker-jwt";
+import { z } from "zod";
+
+// Ensure your key is of the correct length
+const normalizeKey = (key: string, length = 32) => {
+ const encoder = new TextEncoder();
+ const keyBuffer = encoder.encode(key);
+
+ if (keyBuffer.length === length) {
+ return keyBuffer;
+ }
+
+ if (keyBuffer.length > length) {
+ // Truncate the key if it's too long
+ return keyBuffer.slice(0, length);
+ }
+
+ // Pad the key if it's too short
+ const paddedKey = new Uint8Array(length);
+ paddedKey.set(keyBuffer);
+ return paddedKey;
+};
+
+export const encrypt = async (text: string, key: string) => {
+ const enc = new TextEncoder();
+ const keyBuffer = await crypto.subtle.importKey(
+ "raw",
+ normalizeKey(key),
+ { name: "AES-GCM" },
+ false,
+ ["encrypt"]
+ );
+ const iv = crypto.getRandomValues(new Uint8Array(12));
+ const ciphertext = await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv },
+ keyBuffer,
+ enc.encode(text)
+ );
+
+ return Buffer.from([...iv, ...new Uint8Array(ciphertext)]).toString(
+ "base64url"
+ );
+};
+
+export const decrypt = async (ciphertext: string, key: string) => {
+ const keyBuffer = await crypto.subtle.importKey(
+ "raw",
+ normalizeKey(key),
+ { name: "AES-GCM" },
+ false,
+ ["decrypt"]
+ );
+ const data = Uint8Array.from(Buffer.from(ciphertext, "base64url"));
+
+ const decrypted = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv: data.slice(0, 12) },
+ keyBuffer,
+ data.slice(12)
+ );
+ return new TextDecoder().decode(decrypted);
+};
+
+export const verifyChallenge = async (
+ codeVerifier: string,
+ codeChallenge: string
+): Promise<boolean> => {
+ const encoder = new TextEncoder();
+ const data = encoder.encode(codeVerifier);
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
+ const base64Hash = Buffer.from(hashBuffer).toString("base64url");
+
+ return base64Hash === codeChallenge;
+};
+
+const CodeTokenPayload = z.object({
+ userId: z.string(),
+ projectId: z.string(),
+ codeChallenge: z.string(),
+});
+
+type CodeTokenPayload = z.infer<typeof CodeTokenPayload>;
+
+/**
+ * JWT is used because it includes a signature check and expiration,
+ * allowing us to verify in a single call that the token was issued by us and has not expired
+ *
+ * The token is encrypted in accordance with the RFC.
+ *
+ * https://datatracker.ietf.org/doc/html/rfc7636#section-4.4
+ *
+ * Typically, the "code_challenge" and "code_challenge_method" values
+ * are stored in encrypted form in the "code" itself but could
+ * alternatively be stored on the server associated with the code. The
+ * server MUST NOT include the "code_challenge" value in client requests
+ * in a form that other entities can extract.
+ */
+export const createCodeToken = async (
+ payload: CodeTokenPayload,
+ secret: string,
+ options: { maxAge: number }
+) => {
+ const expiresAt = Math.round((Date.now() + options.maxAge) / 1000);
+
+ const jwtKey = await jwt.sign(
+ {
+ iss: "webstudio",
+ sub: `${payload.userId}:${payload.projectId}`,
+ exp: expiresAt,
+ iat: Math.round(Date.now() / 1000),
+ ...payload,
+ },
+ secret
+ );
+
+ return await encrypt(jwtKey, secret);
+};
+
+export const readCodeToken = async (
+ accessToken: string,
+ secret: string
+): Promise<CodeTokenPayload | undefined> => {
+ const jwtToken = await decrypt(accessToken, secret);
+
+ if (false === (await jwt.verify(jwtToken, secret))) {
+ return;
+ }
+
+ const token = await jwt.decode(jwtToken);
+
+ const parsedToken = CodeTokenPayload.parse(token.payload);
+
+ return parsedToken;
+};
+
+const AccessTokenPayload = z.object({
+ userId: z.string(),
+ projectId: z.string(),
+});
+
+type AccessTokenPayload = z.infer<typeof AccessTokenPayload>;
+
+/**
+ * JWT is used because it includes a signature check and expiration,
+ * allowing us to verify in a single call that the token was issued by us and has not expired
+ */
+export const createAccessToken = async (
+ payload: AccessTokenPayload,
+ secret: string,
+ options: { maxAge: number }
+) => {
+ const expiresAt = Math.round((Date.now() + options.maxAge) / 1000);
+
+ return await jwt.sign(
+ {
+ iss: "webstudio",
+ sub: `${payload.userId}:${payload.projectId}`,
+ exp: expiresAt,
+ iat: Math.round(Date.now() / 1000),
+ ...payload,
+ },
+ secret
+ );
+};
+
+export const readAccessToken = async (
+ accessToken: string,
+ secret: string
+): Promise<AccessTokenPayload | undefined> => {
+ if (false === (await jwt.verify(accessToken, secret))) {
+ return;
+ }
+
+ const token = jwt.decode(accessToken);
+
+ const parsedToken = AccessTokenPayload.parse(token.payload);
+
+ return parsedToken;
+};
diff --git a/apps/builder/app/shared/context.server.ts b/apps/builder/app/shared/context.server.ts
index 927014626e..fc45f7bf3b 100644
--- a/apps/builder/app/shared/context.server.ts
+++ b/apps/builder/app/shared/context.server.ts
@@ -8,6 +8,8 @@ import { getUserPlanFeatures } from "./db/user-plan-features.server";
import { staticEnv } from "~/env/env.static.server";
import { createClient } from "@webstudio-is/postrest/index.server";
import { prisma } from "@webstudio-is/prisma-client";
+import { isBuilderUrl } from "./router-utils/origins";
+import { builderAuthenticator } from "~/services/builder-auth.server";
const createAuthorizationContext = async (
request: Request
@@ -19,7 +21,9 @@ const createAuthorizationContext = async (
request.headers.get("x-auth-token") ??
undefined;
- const user = await authenticator.isAuthenticated(request);
+ const user = isBuilderUrl(request.url)
+ ? await builderAuthenticator.isAuthenticated(request)
+ : await authenticator.isAuthenticated(request);
const isServiceCall =
request.headers.has("Authorization") &&
@@ -73,15 +77,9 @@ const createDomainContext = (_request: Request) => {
return context;
};
-const getRequestOrigin = (request: Request) => {
- const url = new URL(request.url);
+const getRequestOrigin = (urlStr: string) => {
+ const url = new URL(urlStr);
- // vercel overwrites x-forwarded-host on edge level even if our header is set
- // as workaround we use custom header x-forwarded-ws-host to get the original host
- url.host =
- request.headers.get("x-forwarded-ws-host") ??
- request.headers.get("x-forwarded-host") ??
- url.host;
return url.origin;
};
@@ -89,7 +87,7 @@ const createDeploymentContext = (request: Request) => {
const context: AppContext["deployment"] = {
deploymentTrpc: trpcSharedClient.deployment,
env: {
- BUILDER_ORIGIN: `${getRequestOrigin(request)}`,
+ BUILDER_ORIGIN: `${getRequestOrigin(request.url)}`,
GITHUB_REF_NAME: staticEnv.GITHUB_REF_NAME ?? "undefined",
GITHUB_SHA: staticEnv.GITHUB_SHA ?? undefined,
},
@@ -130,7 +128,7 @@ const createTrpcCache = () => {
};
};
-const createPostrestContext = () => {
+export const createPostrestContext = () => {
return { client: createClient(env.POSTGREST_URL, env.POSTGREST_API_KEY) };
};
diff --git a/apps/builder/app/shared/debug.ts b/apps/builder/app/shared/debug.ts
new file mode 100644
index 0000000000..a4d16ae82b
--- /dev/null
+++ b/apps/builder/app/shared/debug.ts
@@ -0,0 +1,19 @@
+import createDebugRaw from "debug";
+
+const getModuleName = (url: string) => {
+ const nameParts = url.split("/").pop()?.split(".") ?? [];
+ if (nameParts?.length === 0) {
+ return "unknown";
+ }
+
+ const knownExtensions = ["ts", "tsx", "js", "jsx"];
+
+ if (knownExtensions.includes(nameParts[nameParts.length - 1])) {
+ nameParts.pop();
+ }
+
+ return nameParts.join(".");
+};
+
+export const createDebug = (namespaceOrUrl: string) =>
+ createDebugRaw("ws").extend(getModuleName(namespaceOrUrl));
diff --git a/apps/builder/app/shared/error/error-page.client.tsx b/apps/builder/app/shared/error/error-page.client.tsx
new file mode 100644
index 0000000000..2e17a2fff0
--- /dev/null
+++ b/apps/builder/app/shared/error/error-page.client.tsx
@@ -0,0 +1,46 @@
+import {
+ Toast,
+ Text,
+ TooltipProvider,
+ Flex,
+} from "@webstudio-is/design-system";
+
+export type ErrorPageProps = {
+ error: {
+ message: string;
+ description?: string;
+ };
+ onCloseNavigateTo: string;
+};
+
+export const ErrorPage = (props: ErrorPageProps) => {
+ return (
+ <TooltipProvider>
+ <Flex
+ css={{
+ position: "fixed",
+ inset: 0,
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ <Flex>
+ <Toast
+ variant={"error"}
+ onCopy={() => {
+ navigator.clipboard.writeText(
+ `${props.error.message}\n${props.error.description}`
+ );
+ }}
+ onClose={() => {
+ window.location.href = props.onCloseNavigateTo;
+ }}
+ >
+ <Text variant={"titles"}>{props.error.message}</Text>
+ <Text>{props.error.description}</Text>
+ </Toast>
+ </Flex>
+ </Flex>
+ </TooltipProvider>
+ );
+};
diff --git a/apps/builder/app/shared/router-utils/origins.server.test.ts b/apps/builder/app/shared/router-utils/origins.test.ts
similarity index 79%
rename from apps/builder/app/shared/router-utils/origins.server.test.ts
rename to apps/builder/app/shared/router-utils/origins.test.ts
index 949afe9de3..81b650d192 100644
--- a/apps/builder/app/shared/router-utils/origins.server.test.ts
+++ b/apps/builder/app/shared/router-utils/origins.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "@jest/globals";
-import { parseBuilderUrl } from "./origins.server";
+import { parseBuilderUrl } from "./origins";
test("parseBuilderUrl wstd.dev", async () => {
expect(
@@ -45,7 +45,7 @@ test("parseBuilderUrl development.webstudio.is", async () => {
`);
});
-test("parseBuilderUrl development.webstudio.is", async () => {
+test("parseBuilderUrl main.development.webstudio.is", async () => {
expect(
parseBuilderUrl(
"https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-main.development.webstudio.is"
@@ -53,11 +53,24 @@ test("parseBuilderUrl development.webstudio.is", async () => {
).toMatchInlineSnapshot(`
{
"projectId": "090e6e14-ae50-4b2e-bd22-71733cec05bb",
- "sourceOrigin": "https://development.webstudio.is",
+ "sourceOrigin": "https://main.development.webstudio.is",
}
`);
});
+test("parseBuilderUrl branch.development.webstudio.is", async () => {
+ expect(
+ parseBuilderUrl(
+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-branch.development.webstudio.is"
+ )
+ ).toMatchInlineSnapshot(`
+{
+ "projectId": "090e6e14-ae50-4b2e-bd22-71733cec05bb",
+ "sourceOrigin": "https://branch.development.webstudio.is",
+}
+`);
+});
+
test("parseBuilderUrl apps.webstudio.is", async () => {
expect(
parseBuilderUrl(
diff --git a/apps/builder/app/shared/router-utils/origins.server.ts b/apps/builder/app/shared/router-utils/origins.ts
similarity index 62%
rename from apps/builder/app/shared/router-utils/origins.server.ts
rename to apps/builder/app/shared/router-utils/origins.ts
index bd46ebc487..a87ac74148 100644
--- a/apps/builder/app/shared/router-utils/origins.server.ts
+++ b/apps/builder/app/shared/router-utils/origins.ts
@@ -1,13 +1,6 @@
-export const getRequestOrigin = (request: Request) => {
- const url = new URL(request.url);
+export const getRequestOrigin = (urlStr: string) => {
+ const url = new URL(urlStr);
- // Vercel overwrites x-forwarded-host at the edge level, even if our header is set.
- // We use custom header x-forwarded-ws-host to get the original host as a workaround.
- url.host =
- request.headers.get("x-forwarded-ws-host") ??
- request.headers.get("x-forwarded-host") ??
- url.host;
- url.protocol = request.headers.get("x-forwarded-proto") ?? "https";
return url.origin;
};
@@ -33,6 +26,7 @@ export const parseBuilderUrl = (urlStr: string) => {
// Extract prefix, projectId (UUID), and branch (if exists)
const prefix = match?.groups?.prefix;
const projectId = match?.groups?.uuid;
+ const branch = match?.groups?.branch;
if (prefix !== buildProjectDomainPrefix) {
return {
@@ -48,7 +42,7 @@ export const parseBuilderUrl = (urlStr: string) => {
};
}
- fragments[0] = fragments[0].replace(re, "");
+ fragments[0] = fragments[0].replace(re, branch ?? "");
const sourceUrl = new URL(url.origin);
sourceUrl.protocol = "https";
@@ -65,17 +59,8 @@ export const isBuilderUrl = (urlStr: string): boolean => {
return projectId !== undefined;
};
-export function getAuthorizationServerOrigin(request: Request): string;
-export function getAuthorizationServerOrigin(origin: string): string;
-
-// eslint-disable-next-line func-style
-export function getAuthorizationServerOrigin(
- request: string | Request
-): string {
- const origin =
- typeof request === "string"
- ? new URL(request).origin
- : getRequestOrigin(request);
+export const getAuthorizationServerOrigin = (urlStr: string): string => {
+ const origin = getRequestOrigin(urlStr);
const { sourceOrigin } = parseBuilderUrl(origin);
return sourceOrigin;
-}
+};
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index 260fb8c1dc..de0d104cd8 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -2,6 +2,7 @@ import type { AUTH_PROVIDERS } from "~/shared/session";
import type { Project } from "@webstudio-is/project";
import { $authToken } from "../nano-states";
import { publicStaticEnv } from "~/env/env.static";
+import { getAuthorizationServerOrigin } from "./origins";
const searchParams = (params: Record<string, string | undefined | null>) => {
const searchParams = new URLSearchParams();
@@ -55,6 +56,38 @@ export const builderUrl = (props: {
return url.href;
};
+export const builderUrlNew = (props: {
+ projectId: string;
+ pageId?: string;
+ origin: string;
+ authToken?: string;
+ mode?: "edit" | "preview";
+}) => {
+ const authServerOrigin = getAuthorizationServerOrigin(props.origin);
+
+ // const { projectId, pageId, authToken } = props;
+ const url = new URL(
+ "/", // builderPath({ projectId, pageId, authToken }),
+ authServerOrigin
+ );
+
+ const fragments = url.host.split(".");
+ if (fragments.length <= 3) {
+ fragments.splice(0, 0, "p-" + props.projectId);
+ } else {
+ // staging | development branches
+ fragments[0] = "p-" + props.projectId + "-dot-" + fragments[0];
+ }
+
+ url.host = fragments.join(".");
+
+ if (props.mode !== undefined) {
+ url.searchParams.set("mode", props.mode);
+ }
+
+ return url.href;
+};
+
export const dashboardPath = () => {
return "/dashboard";
};
diff --git a/apps/builder/package.json b/apps/builder/package.json
index 788ed33025..8eec6aa435 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -11,6 +11,7 @@
"build:webflow-presets": "pnpm css-to-ws ./app/shared/copy-paste/plugin-webflow/style-presets.css ./app/shared/copy-paste/plugin-webflow/__generated__/style-presets.ts",
"start": "remix-serve build/server/index.js",
"dev": "remix vite:dev",
+ "dev:auth": "DEBUG=OAuth2Strategy,ws:* remix vite:dev",
"typecheck": "tsc --noEmit --emitDeclarationOnly false",
"test": "NODE_OPTIONS=--experimental-vm-modules jest",
"ci:migrate": "migrations migrate"
@@ -48,6 +49,7 @@
"@remix-run/server-runtime": "^2.11.0",
"@trpc/client": "^10.45.2",
"@trpc/server": "^10.45.2",
+ "@tsndr/cloudflare-worker-jwt": "^2.5.3",
"@vercel/remix": "2.11.0",
"@webstudio-is/ai": "workspace:*",
"@webstudio-is/asset-uploader": "workspace:*",
@@ -80,6 +82,7 @@
"cookie": "^0.6.0",
"css-tree": "^2.3.1",
"date-fns": "^3.6.0",
+ "debug": "^4.3.6",
"detect-font": "^0.1.5",
"downshift": "^6.1.7",
"fast-deep-equal": "^3.1.3",
@@ -105,6 +108,7 @@
"remix-auth-form": "^1.5.0",
"remix-auth-github": "^1.7.0",
"remix-auth-google": "^2.0.0",
+ "remix-auth-oauth2": "^2.3.0",
"shallow-equal": "^3.1.0",
"slugify": "^1.6.6",
"strip-indent": "^4.0.0",
@@ -115,13 +119,15 @@
"urlpattern-polyfill": "^9.0.0",
"use-debounce": "^9.0.4",
"warn-once": "^0.1.1",
- "zod": "^3.22.4"
+ "zod": "^3.22.4",
+ "zod-validation-error": "^3.3.1"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@remix-run/dev": "^2.11.0",
"@testing-library/react-hooks": "^8.0.1",
"@types/cookie": "^0.6.0",
+ "@types/debug": "^4.1.12",
"@types/prismjs": "^1.26.0",
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
diff --git a/apps/builder/vite.config.ts b/apps/builder/vite.config.ts
index 9fda34aea6..6631a34afc 100644
--- a/apps/builder/vite.config.ts
+++ b/apps/builder/vite.config.ts
@@ -6,7 +6,7 @@ import type { IncomingMessage } from "node:http";
import {
getAuthorizationServerOrigin,
isBuilderUrl,
-} from "./app/shared/router-utils/origins.server";
+} from "./app/shared/router-utils/origins";
import { readFileSync } from "node:fs";
export default defineConfig(({ mode }) => {
@@ -53,13 +53,12 @@ export default defineConfig(({ mode }) => {
key: readFileSync("../../https/privkey.pem"),
cert: readFileSync("../../https/fullchain.pem"),
},
-
cors: ((
req: IncomingMessage,
callback: (error: Error | null, options: CorsOptions | null) => void
) => {
// Handle CORS preflight requests in development to mimic Remix production behavior
- if (req.method === "OPTIONS") {
+ if (req.method === "OPTIONS" || req.method === "GET") {
if (req.headers.origin != null && req.url != null) {
const url = new URL(req.url, `https://${req.headers.host}`);
@@ -73,11 +72,13 @@ export default defineConfig(({ mode }) => {
}
}
- // Respond with method not allowed for other preflight requests
- return callback(null, {
- preflightContinue: false,
- optionsSuccessStatus: 405,
- });
+ if (req.method === "OPTIONS") {
+ // Respond with method not allowed for other preflight requests
+ return callback(null, {
+ preflightContinue: false,
+ optionsSuccessStatus: 405,
+ });
+ }
}
// Disable CORS for all other requests
diff --git a/package.json b/package.json
index e1d2c833f0..6c07c61806 100644
--- a/package.json
+++ b/package.json
@@ -88,7 +88,8 @@
"@stitches/[email protected]": "patches/@[email protected]",
"@types/[email protected]": "patches/@[email protected]",
- "@radix-ui/[email protected]": "patches/@[email protected]"
+ "@radix-ui/[email protected]": "patches/@[email protected]",
+ "@remix-run/[email protected]": "patches/@[email protected]"
}
}
}
diff --git a/packages/trpc-interface/src/authorize/project.server.ts b/packages/trpc-interface/src/authorize/project.server.ts
index 153283217f..93ea7ce79f 100644
--- a/packages/trpc-interface/src/authorize/project.server.ts
+++ b/packages/trpc-interface/src/authorize/project.server.ts
@@ -15,12 +15,15 @@ type CheckInput = {
};
};
-const check = async (context: AppContext, input: CheckInput) => {
+const check = async (
+ postgrestClient: AppContext["postgrest"]["client"],
+ input: CheckInput
+) => {
const { subjectSet } = input;
if (subjectSet.namespace === "User") {
// We check only if the user is the owner of the project
- const row = await context.postgrest.client
+ const row = await postgrestClient
.from("Project")
.select("id")
.eq("id", input.id)
@@ -41,7 +44,7 @@ const check = async (context: AppContext, input: CheckInput) => {
} as const;
if (subjectSet.namespace === "Token" && input.permit !== "own") {
- const row = await context.postgrest.client
+ const row = await postgrestClient
.from("AuthorizationToken")
.select("token")
.eq("token", subjectSet.id)
@@ -64,97 +67,130 @@ const memoizedCheck = memoize(check, {
cacheKey: ([_context, input]) => JSON.stringify(input),
});
-export const hasProjectPermit = async (
- props: {
- projectId: string;
- permit: AuthPermit;
- },
- context: AppContext
+type AuthInfo =
+ | {
+ type: "user";
+ userId: string;
+ }
+ | {
+ type: "token";
+ authToken: string;
+ }
+ | {
+ type: "service";
+ };
+
+export const checkProjectPermit = async (
+ projectId: string,
+ permit: AuthPermit,
+ authInfo: AuthInfo,
+ postgrestClient: AppContext["postgrest"]["client"]
) => {
- const start = Date.now();
-
- try {
- const { authorization } = context;
+ const checks = [];
+ const namespace = "Project";
- const checks = [];
- const namespace = "Project";
+ if (authInfo.type === "service") {
+ return permit === "view";
+ }
- // Allow load production build env i.e. "published" project
- if (props.permit === "view" && authorization.isServiceCall) {
- return true;
- }
+ // @todo Delete and use tokens
+ const templateIds = [
+ // Production
+ "5e086cf4-4293-471c-8eab-ddca8b5cd4db",
+ "94e6e1b8-c6c4-485a-9d7a-8282e11920c0",
+ "05954204-fcee-407e-b47f-77a38de74431",
+ "afc162c2-6396-41b7-a855-8fc04604a7b1",
+ // Staging IDs
+ "e3dd56f9-ffd9-4692-8a61-e835de822e21",
+ "90b41d4e-f5e9-48d6-a954-6249b146852a",
+ ];
+
+ // @todo Delete and use tokens
+ if (permit === "view" && templateIds.includes(projectId)) {
+ return true;
+ }
- // @todo Delete and use tokens
- const templateIds = [
- // Production
- "5e086cf4-4293-471c-8eab-ddca8b5cd4db",
- "94e6e1b8-c6c4-485a-9d7a-8282e11920c0",
- "05954204-fcee-407e-b47f-77a38de74431",
- "afc162c2-6396-41b7-a855-8fc04604a7b1",
- // Staging IDs
- "e3dd56f9-ffd9-4692-8a61-e835de822e21",
- "90b41d4e-f5e9-48d6-a954-6249b146852a",
- ];
-
- // @todo Delete and use tokens
- if (props.permit === "view" && templateIds.includes(props.projectId)) {
- return true;
+ if (authInfo.type === "token") {
+ // Token doesn't have "own" permit, do not check it
+ if (permit === "own") {
+ return false;
}
- // Check if the user is allowed to access the project
- if (authorization.userId !== undefined) {
- checks.push(
- memoizedCheck(context, {
- subjectSet: {
- namespace: "User",
- id: authorization.userId,
- },
- namespace,
- id: props.projectId,
- permit: props.permit,
- })
- );
- }
+ checks.push(
+ memoizedCheck(postgrestClient, {
+ namespace,
+ id: projectId,
+ subjectSet: {
+ id: authInfo.authToken,
+ namespace: "Token",
+ },
+ permit: permit,
+ })
+ );
+ }
- // Check if the special link with a token allows to access the project
- // Token doesn't have own permit, do not check it
- if (authorization.authToken !== undefined && props.permit !== "own") {
- checks.push(
- memoizedCheck(context, {
- namespace,
- id: props.projectId,
- subjectSet: {
- id: authorization.authToken,
- namespace: "Token",
- },
- permit: props.permit,
- })
- );
- }
+ // Check if the user is allowed to access the project
+ if (authInfo.type === "user") {
+ checks.push(
+ memoizedCheck(postgrestClient, {
+ subjectSet: {
+ namespace: "User",
+ id: authInfo.userId,
+ },
+ namespace,
+ id: projectId,
+ permit: permit,
+ })
+ );
+ }
- if (checks.length === 0) {
- return false;
- }
+ if (checks.length === 0) {
+ return false;
+ }
- const authResults = await Promise.allSettled(checks);
+ const authResults = await Promise.allSettled(checks);
- for (const authResult of authResults) {
- if (authResult.status === "rejected") {
- throw new Error(`Authorization call failed ${authResult.reason}`);
- }
+ for (const authResult of authResults) {
+ if (authResult.status === "rejected") {
+ throw new Error(`Authorization call failed ${authResult.reason}`);
}
+ }
- const allowed = authResults.some(
- (authResult) =>
- authResult.status === "fulfilled" && authResult.value.allowed
- );
+ const allowed = authResults.some(
+ (authResult) =>
+ authResult.status === "fulfilled" && authResult.value.allowed
+ );
- return allowed;
- } finally {
- const diff = Date.now() - start;
+ return allowed;
+};
- console.info(`hasProjectPermit execution ${diff}ms`);
+export const hasProjectPermit = async (
+ props: {
+ projectId: string;
+ permit: AuthPermit;
+ },
+ context: AppContext
+) => {
+ 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 (authInfo === undefined) {
+ return false;
}
+
+ return checkProjectPermit(
+ props.projectId,
+ props.permit,
+ authInfo,
+ context.postgrest.client
+ );
};
/**
@@ -169,29 +205,21 @@ export const getProjectPermit = async <T extends AuthPermit>(
},
context: AppContext
): Promise<T | undefined> => {
- const start = Date.now();
+ const permitToCheck = props.permits;
- try {
- const permitToCheck = props.permits;
+ const permits = await Promise.allSettled(
+ permitToCheck.map((permit) =>
+ hasProjectPermit({ projectId: props.projectId, permit }, context)
+ )
+ );
- const permits = await Promise.allSettled(
- permitToCheck.map((permit) =>
- hasProjectPermit({ projectId: props.projectId, permit }, context)
- )
- );
-
- for (const permit of permits) {
- if (permit.status === "rejected") {
- throw new Error(`Authorization call failed ${permit.reason}`);
- }
-
- if (permit.value === true) {
- return permitToCheck[permits.indexOf(permit)];
- }
+ for (const permit of permits) {
+ if (permit.status === "rejected") {
+ throw new Error(`Authorization call failed ${permit.reason}`);
}
- } finally {
- const diff = Date.now() - start;
- console.info(`getProjectPermit execution ${diff}ms`);
+ if (permit.value === true) {
+ return permitToCheck[permits.indexOf(permit)];
+ }
}
};
diff --git a/patches/@[email protected] b/patches/@[email protected]
new file mode 100644
index 0000000000..d93b1b026a
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,13 @@
+diff --git a/dist/vite/node-adapter.js b/dist/vite/node-adapter.js
+index 27cafca56bde2e5c086723b20bcfa50169bb38ea..b851e038e0fe8f73d193a2ca3ff2c0c13c82191e 100644
+--- a/dist/vite/node-adapter.js
++++ b/dist/vite/node-adapter.js
+@@ -36,7 +36,7 @@ function fromNodeHeaders(nodeHeaders) {
+
+ // Based on `createRemixRequest` in packages/remix-express/server.ts
+ function fromNodeRequest(nodeReq) {
+- let origin = nodeReq.headers.origin && "null" !== nodeReq.headers.origin ? nodeReq.headers.origin : `http://${nodeReq.headers.host}`;
++ let origin = `https://${nodeReq.headers.host}`;
+ // Use `req.originalUrl` so Remix is aware of the full path
+ invariant["default"](nodeReq.originalUrl, "Expected `nodeReq.originalUrl` to be defined");
+ let url = new URL(nodeReq.originalUrl, origin);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2fcd2eb042..5500e6a769 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -14,6 +14,9 @@ patchedDependencies:
'@radix-ui/[email protected]':
hash: 5y6bqj6dymxto7bikr5opyo7lm
path: patches/@[email protected]
+ '@remix-run/[email protected]':
+ hash: zolvyaomi7vkkka7op77fpjpau
+ path: patches/@[email protected]
'@stitches/[email protected]':
hash: knml42mpr6mlzseo3d6gjljiq4
path: patches/@[email protected]
@@ -217,9 +220,12 @@ importers:
'@trpc/server':
specifier: ^10.45.2
version: 10.45.2
+ '@tsndr/cloudflare-worker-jwt':
+ specifier: ^2.5.3
+ version: 2.5.3
'@vercel/remix':
specifier: 2.11.0
'@webstudio-is/ai':
specifier: workspace:*
version: link:../../packages/ai
@@ -313,6 +319,9 @@ importers:
date-fns:
specifier: ^3.6.0
version: 3.6.0
+ debug:
+ specifier: ^4.3.6
+ version: 4.3.6
detect-font:
specifier: ^0.1.5
version: 0.1.5
@@ -388,6 +397,9 @@ importers:
remix-auth-google:
specifier: ^2.0.0
+ remix-auth-oauth2:
+ specifier: ^2.3.0
shallow-equal:
specifier: ^3.1.0
version: 3.1.0
@@ -421,19 +433,25 @@ importers:
zod:
specifier: ^3.22.4
version: 3.22.4
+ zod-validation-error:
+ specifier: ^3.3.1
+ version: 3.3.1([email protected])
devDependencies:
'@jest/globals':
specifier: ^29.7.0
version: 29.7.0
'@remix-run/dev':
specifier: ^2.11.0
'@testing-library/react-hooks':
specifier: ^8.0.1
'@types/cookie':
specifier: ^0.6.0
version: 0.6.0
+ '@types/debug':
+ specifier: ^4.1.12
+ version: 4.1.12
'@types/prismjs':
specifier: ^1.26.0
version: 1.26.0
@@ -579,7 +597,7 @@ importers:
version: 4.20240701.0
'@remix-run/dev':
specifier: 2.11.0
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -640,7 +658,7 @@ importers:
devDependencies:
'@remix-run/dev':
specifier: 2.11.0
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -704,7 +722,7 @@ importers:
devDependencies:
'@remix-run/dev':
specifier: 2.11.0
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -768,7 +786,7 @@ importers:
devDependencies:
'@remix-run/dev':
specifier: 2.11.0
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -826,7 +844,7 @@ importers:
devDependencies:
'@remix-run/dev':
specifier: 2.11.0
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -1043,7 +1061,7 @@ importers:
version: 2.11.0(@cloudflare/[email protected])([email protected])
'@remix-run/dev':
specifier: ^2.11.0
'@remix-run/node':
specifier: ^2.11.0
version: 2.11.0([email protected])
@@ -4034,6 +4052,21 @@ packages:
resolution: {integrity: sha512-gGq0NJkIGSwdbUt4yhdF8ZrmkGKVz9vAdVzpOfnom+V8PLSmSOVhZwbNvZZS1EYcJN5hzzKBxmmVVAInM6HQLg==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ '@oslojs/[email protected]':
+ resolution: {integrity: sha512-cZOLRzKfv3JTxIzNTAoiN0+utB0is9cQOOp5Xq++SE8MtIXXDLFblZGFrHCdTXLGXvUZmopeB/dFZrkh5MpKqQ==}
+
+ '@oslojs/[email protected]':
+ resolution: {integrity: sha512-xi1MOhP7t9TFV1nOmzG0qIdCXdFXbeMYskhfI5eakBlU8re/xO+qjdyiBO+hl+nK4z4lZWCDjlgH8BXUWQDWFw==}
+
+ '@oslojs/[email protected]':
+ resolution: {integrity: sha512-2y39MOLkkCvaBdi2TrBDtk7106fayDHRLz11K1/UvtW28VgL5/TbV/tPRTmSA5dhvQQqLYDJj3zsBkjeP+aD2w==}
+
+ '@oslojs/[email protected]':
+ resolution: {integrity: sha512-hkjo6MuIK/kQR5CrGNdAPZhS01ZCXuWDRJ187zh6qqF2+yMHZpD9fAYpX8q2bOO6Ryhl3XpCT6kUX76N8hhm4Q==}
+
+ '@oslojs/[email protected]':
+ resolution: {integrity: sha512-t70+e4EgnzTbU4MrUWXzqWN2A6RJrlSSvwwuBv6E0Ap6/nsIXrjsdRWeTcSvvXTcC6fi0YdWaqEWLipcEm2Cgw==}
+
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
@@ -5155,6 +5188,9 @@ packages:
'@ts-morph/[email protected]':
resolution: {integrity: sha512-7hWZS0NRpEsNV8vWJzg7FEz6V8MaLNeJOmwmghqUXTpzk16V1LLZhdo+4QvE/+zv4cVci0OviuJFnqhEfoV3+g==}
+ '@tsndr/[email protected]':
+ resolution: {integrity: sha512-zbdvjRG86y/ObiBgTJrzBC39t2FcaeGwB6AV7VO4LvHKJNyZvLYRbKT68eaoJhnJldyHhs7yZ69neRVdUd9knA==}
+
resolution: {integrity: sha512-veQTnWP+1D/xbxVrPC3zHnCZRjSrKfhbMUlEA43iMZLu7EsnTtkJklIuwrCPbOi8YkvDQAiW05VQQFvvz9oieQ==}
@@ -5194,6 +5230,9 @@ packages:
resolution: {integrity: sha512-3m636Jz4d9d+lHVMp6FNLsUWQrfOx1xpm1SBxPbQYSNNgXMe+XswcsDeo1ldyULiuzYyWKk1kmvkLTgNq+215Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}
+
resolution: {integrity: sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==}
@@ -6130,6 +6169,15 @@ packages:
supports-color:
optional: true
+ resolution: {integrity: sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==}
+ engines: {node: '>=6.0'}
+ peerDependencies:
+ supports-color: '*'
+ peerDependenciesMeta:
+ supports-color:
+ optional: true
+
resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==}
@@ -8766,6 +8814,22 @@ packages:
'@remix-run/server-runtime': ^1.0.0 || ^2.0.0
remix-auth: ^3.6.0
+ resolution: {integrity: sha512-94PztjpER9hethzZOpF1lqwlmLccGY7RUKp9ua3Ii3DBPqVIO/hFedeqpcvZyysbPaW3sK3ztqfe8b8nnF4F/Q==}
+ engines: {node: ^18.0.0 || ^20.0.0 || >=20.0.0}
+ peerDependencies:
+ '@remix-run/cloudflare': ^1.0.0 || ^2.0.0
+ '@remix-run/deno': ^1.0.0 || ^2.0.0
+ '@remix-run/node': ^1.0.0 || ^2.0.0
+ remix-auth: ^3.6.0
+ peerDependenciesMeta:
+ '@remix-run/cloudflare':
+ optional: true
+ '@remix-run/deno':
+ optional: true
+ '@remix-run/node':
+ optional: true
+
resolution: {integrity: sha512-2QVjp2nJVaYxuFBecMQwzixCO7CLSssttLBU5eVlNcNlVeNMmY1g7OkmZ1Ogw9sBcoMXZ18J7xXSK0AISVFcfQ==}
peerDependencies:
@@ -9857,6 +9921,12 @@ packages:
peerDependencies:
zod: ^3.21.4
+ resolution: {integrity: sha512-uFzCZz7FQis256dqw4AhPQgD6f3pzNca/Zh62RNELavlumQB3nDIUFbF5JQfFLcMbO1s02Q7Xg/gpcOBlEnYZA==}
+ engines: {node: '>=18.0.0'}
+ peerDependencies:
+ zod: ^3.18.0
+
resolution: {integrity: sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==}
@@ -9920,7 +9990,7 @@ snapshots:
'@babel/traverse': 7.24.1
'@babel/types': 7.24.0
convert-source-map: 1.9.0
- debug: 4.3.4
+ debug: 4.3.6
gensync: 1.0.0-beta.2
json5: 2.2.3
semver: 6.3.1
@@ -11965,6 +12035,21 @@ snapshots:
dependencies:
which: 3.0.1
+ '@oslojs/[email protected]':
+ dependencies:
+ '@oslojs/binary': 0.4.0
+
+ '@oslojs/[email protected]': {}
+
+ '@oslojs/[email protected]':
+ dependencies:
+ '@oslojs/asn1': 0.2.3
+ '@oslojs/binary': 0.4.0
+
+ '@oslojs/[email protected]': {}
+
+ '@oslojs/[email protected]': {}
+
optional: true
@@ -12715,7 +12800,7 @@ snapshots:
optionalDependencies:
typescript: 5.5.2
dependencies:
'@babel/core': 7.24.5
'@babel/generator': 7.24.5
@@ -13245,6 +13330,8 @@ snapshots:
mkdirp: 1.0.4
path-browserify: 1.0.1
+ '@tsndr/[email protected]': {}
+
dependencies:
'@types/estree': 1.0.5
@@ -13299,6 +13386,10 @@ snapshots:
'@types/[email protected](patch_hash=ac22lciodhaj6xmoeignv36gyq)': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/ms': 0.7.31
+
dependencies:
'@types/ms': 0.7.31
@@ -13620,9 +13711,9 @@ snapshots:
'@vanilla-extract/[email protected]': {}
dependencies:
'@remix-run/node': 2.11.0([email protected])
'@remix-run/server-runtime': 2.11.0([email protected])
'@vercel/static-config': 3.0.0
@@ -14378,6 +14469,10 @@ snapshots:
dependencies:
ms: 2.1.2
+ dependencies:
+ ms: 2.1.2
+
@@ -17804,12 +17899,25 @@ snapshots:
dependencies:
'@remix-run/server-runtime': 2.11.0([email protected])
- debug: 4.3.4
+ debug: 4.3.6
uuid: 9.0.1
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@oslojs/crypto': 0.6.2
+ '@oslojs/encoding': 0.4.1
+ '@oslojs/oauth2': 0.5.0
+ debug: 4.3.6
+ optionalDependencies:
+ '@remix-run/cloudflare': 2.11.0(@cloudflare/[email protected])([email protected])
+ '@remix-run/node': 2.11.0([email protected])
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
@@ -18732,7 +18840,7 @@ snapshots:
dependencies:
cac: 6.7.14
- debug: 4.3.4
+ debug: 4.3.6
pathe: 1.1.2
picocolors: 1.0.1
vite: 5.4.0(@types/[email protected])
@@ -18967,6 +19075,10 @@ snapshots:
dependencies:
zod: 3.22.4
+ dependencies:
+ zod: 3.22.4
+