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: align path rules with published routes and document headers (#6488)

Oleg Isonen00fcb26afe47
diff --git a/apps/builder/app/builder/features/address-bar.tsx b/apps/builder/app/builder/features/address-bar.tsx
index 3cf2711748..b69ca599cd 100644
--- a/apps/builder/app/builder/features/address-bar.tsx
+++ b/apps/builder/app/builder/features/address-bar.tsx
@@ -29,9 +29,10 @@ import { CheckMarkIcon, CopyIcon, DynamicPageIcon } from "@webstudio-is/icons";
import {
compilePathnamePattern,
isPathnamePattern,
- matchUrlPattern,
tokenizePathnamePattern,
} from "@webstudio-is/project-build/runtime";
+import { matchPathnamePattern } from "@webstudio-is/wsauth";
+import { toWebstudioParams } from "@webstudio-is/react-sdk";
import {
$selectedPage,
$selectedPagePath,
@@ -260,7 +261,7 @@ const AddressBar = forwardRef<
const path = useStore($selectedPagePath);
let history = useStore($selectedPageHistory);
history = useMemo(() => {
- return history.filter((item) => matchUrlPattern(path, item));
+ return history.filter((item) => matchPathnamePattern(path, item));
}, [history, path]);
const [pathParams, setPathParams] = useState(
() => $currentSystem.get().params
@@ -308,7 +309,9 @@ const AddressBar = forwardRef<
options={history}
onSelect={(option) => {
flushSync(() => {
- setPathParams(matchUrlPattern(path, option) ?? {});
+ setPathParams(
+ toWebstudioParams(path, matchPathnamePattern(path, option) ?? {})
+ );
});
containerRef.current?.requestSubmit();
}}
diff --git a/apps/builder/app/canvas/interceptor.ts b/apps/builder/app/canvas/interceptor.ts
index 0a122f5a4f..8637e4313a 100644
--- a/apps/builder/app/canvas/interceptor.ts
+++ b/apps/builder/app/canvas/interceptor.ts
@@ -1,15 +1,15 @@
import { getAllPages, getPagePath, isAbsoluteUrl } from "@webstudio-is/sdk";
import {
compilePathnamePattern,
- matchUrlPattern,
tokenizePathnamePattern,
} from "@webstudio-is/project-build/runtime";
+import { matchPathnameRoutes } from "@webstudio-is/wsauth";
+import { toWebstudioParams } from "@webstudio-is/react-sdk";
import { $selectedPage } from "~/shared/nano-states";
import { selectPage } from "~/shared/nano-states";
import { $isPreviewMode, $selectedPageHash } from "~/shared/nano-states";
import { $pages } from "~/shared/sync/data-stores";
import { $currentSystem, updateCurrentSystem } from "~/shared/system";
-import { comparePatterns } from "./shared/routing-priority";
const getSelectedPagePathname = () => {
const pages = $pages.get();
@@ -45,26 +45,28 @@ const switchPageAndUpdateSystem = (href: string, formData?: FormData) => {
}
}
const pageHref = new URL(href, "https://any-valid.url");
- // sort pages before matching to not depend on order of page creation
- const sortedPages = getAllPages(pages).toSorted((leftPage, rightPage) =>
- comparePatterns(leftPage.path, rightPage.path)
+ const matchedPage = matchPathnameRoutes(
+ getAllPages(pages).map((page) => ({
+ pattern: getPagePath(page.id, pages),
+ value: page,
+ })),
+ pageHref.pathname
);
- for (const page of sortedPages) {
- const pagePath = getPagePath(page.id, pages);
- const params = matchUrlPattern(pagePath, pageHref.pathname);
- if (params) {
- // populate search params with form data values if available
- if (formData) {
- for (const [key, value] of formData.entries()) {
- pageHref.searchParams.set(key, value.toString());
- }
+ if (matchedPage) {
+ const { value: page, params } = matchedPage;
+ // populate search params with form data values if available
+ if (formData) {
+ for (const [key, value] of formData.entries()) {
+ pageHref.searchParams.set(key, value.toString());
}
- const search = Object.fromEntries(pageHref.searchParams);
- $selectedPageHash.set({ hash: pageHref.hash });
- selectPage(page.id);
- updateCurrentSystem({ params, search });
- break;
}
+ const search = Object.fromEntries(pageHref.searchParams);
+ $selectedPageHash.set({ hash: pageHref.hash });
+ selectPage(page.id);
+ updateCurrentSystem({
+ params: toWebstudioParams(getPagePath(page.id, pages), params),
+ search,
+ });
}
};
diff --git a/apps/builder/app/canvas/shared/routing-priority.test.ts b/apps/builder/app/canvas/shared/routing-priority.test.ts
deleted file mode 100644
index b771a9ee8f..0000000000
--- a/apps/builder/app/canvas/shared/routing-priority.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { test, expect } from "vitest";
-import { comparePatterns } from "./routing-priority";
-
-test("sort top-level patterns", () => {
- const patterns = ["/foo*", "/:foo", "/foo"];
- const expected = ["/foo", "/:foo", "/foo*"];
- expect(patterns.toSorted(comparePatterns)).toEqual(expected);
-});
-
-test("sort static paths", () => {
- const patterns = ["/a/z", "/a/b/c", "/a/c", "/a/b"];
- const expected = ["/a/b", "/a/c", "/a/z", "/a/b/c"];
- expect(patterns.toSorted(comparePatterns)).toEqual(expected);
-});
-
-test("sort mixed static, dynamic, spread at multiple levels", () => {
- const patterns = [
- "/foo",
- "/:id",
- "/bar*",
- "/foo/bar",
- "/foo/:id",
- "/foo/bar*",
- ];
- const expected = [
- // static first-segment
- "/foo",
- "/foo/bar",
- "/foo/:id",
- "/foo/bar*",
- // dynamic then spread at top level
- "/:id",
- "/bar*",
- ];
- expect(patterns.toSorted(comparePatterns)).toEqual(expected);
-});
-
-test("sort deeply nested mixed segments", () => {
- const patterns = ["/u/bar", "/u/:id", "/u/bar/b", "/u/:id/c", "/u/bar/*"];
- const expected = [
- // static second-segment
- "/u/bar",
- "/u/bar/b",
- "/u/bar/*",
- // dynamic second-segment
- "/u/:id",
- "/u/:id/c",
- ];
- expect(patterns.toSorted(comparePatterns)).toEqual(expected);
-});
diff --git a/apps/builder/app/canvas/shared/routing-priority.ts b/apps/builder/app/canvas/shared/routing-priority.ts
deleted file mode 100644
index 17e8a4d060..0000000000
--- a/apps/builder/app/canvas/shared/routing-priority.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-const STATIC = 1;
-const DYNAMIC = 2;
-const SPREAD = 3;
-
-const getSegmentScore = (segment: string) => {
- // give spread the least priority
- if (segment.endsWith("*")) {
- return SPREAD;
- }
- // sort dynamic segments before splat
- if (segment.startsWith(":")) {
- return DYNAMIC;
- }
- // sort static routes before dynamic routes
- return STATIC;
-};
-
-export const comparePatterns = (leftPattern: string, rightPattern: string) => {
- const leftSegments = leftPattern.split("/");
- const rightSegments = rightPattern.split("/");
- const commonLength = Math.min(leftSegments.length, rightSegments.length);
-
- // compare each segment first
- for (let index = 0; index < commonLength; index++) {
- const leftScore = getSegmentScore(leftSegments[index]);
- const rightScore = getSegmentScore(rightSegments[index]);
- if (leftScore !== rightScore) {
- return leftScore - rightScore;
- }
- }
-
- // compare amount of segments
- const leftLength = leftSegments.length;
- const rightLength = rightSegments.length;
- if (leftLength !== rightLength) {
- return leftLength - rightLength;
- }
-
- // sort alphabetically
- return leftPattern.localeCompare(rightPattern);
-};
diff --git a/apps/builder/app/shared/system.test.ts b/apps/builder/app/shared/system.test.ts
index 916492449d..62315c3917 100644
--- a/apps/builder/app/shared/system.test.ts
+++ b/apps/builder/app/shared/system.test.ts
@@ -45,6 +45,30 @@ const getInitialPages = (page: Page): Pages => ({
]),
});
+const getPagesInBlogFolder = (page: Page): Pages => ({
+ ...getInitialPages(page),
+ folders: new Map([
+ [
+ "rootId",
+ {
+ id: "rootId",
+ name: "",
+ slug: "",
+ children: ["homeId", "folderId"],
+ },
+ ],
+ [
+ "folderId",
+ {
+ id: "folderId",
+ name: "Blog",
+ slug: "blog",
+ children: ["dynamicId"],
+ },
+ ],
+ ]),
+});
+
describe("history", () => {
test("add new path at the start", () => {
$pages.set(
@@ -100,36 +124,16 @@ describe("history", () => {
});
test("system pathname includes parent folder slug", () => {
- $pages.set({
- ...getInitialPages({
+ $pages.set(
+ getPagesInBlogFolder({
id: "dynamicId",
path: "/post/:slug",
name: "",
title: "",
meta: {},
rootInstanceId: "",
- }),
- folders: new Map([
- [
- "rootId",
- {
- id: "rootId",
- name: "",
- slug: "",
- children: ["homeId", "folderId"],
- },
- ],
- [
- "folderId",
- {
- id: "folderId",
- name: "Blog",
- slug: "blog",
- children: ["dynamicId"],
- },
- ],
- ]),
- });
+ })
+ );
selectPage("dynamicId");
updateCurrentSystem({
@@ -143,8 +147,8 @@ test("system pathname includes parent folder slug", () => {
});
test("system params support legacy history without parent folder slug", () => {
- $pages.set({
- ...getInitialPages({
+ $pages.set(
+ getPagesInBlogFolder({
id: "dynamicId",
path: "/post/:slug",
name: "",
@@ -152,28 +156,8 @@ test("system params support legacy history without parent folder slug", () => {
meta: {},
rootInstanceId: "",
history: ["/post/my-post"],
- }),
- folders: new Map([
- [
- "rootId",
- {
- id: "rootId",
- name: "",
- slug: "",
- children: ["homeId", "folderId"],
- },
- ],
- [
- "folderId",
- {
- id: "folderId",
- name: "Blog",
- slug: "blog",
- children: ["dynamicId"],
- },
- ],
- ]),
- });
+ })
+ );
selectPage("dynamicId");
expect($currentSystem.get()).toMatchObject({
@@ -181,3 +165,20 @@ test("system params support legacy history without parent folder slug", () => {
pathname: "/blog/post/my-post",
});
});
+
+test("system params decode history paths with an encoded folder slug", () => {
+ $pages.set(
+ getPagesInBlogFolder({
+ id: "dynamicId",
+ path: "/post/:slug",
+ name: "",
+ title: "",
+ meta: {},
+ rootInstanceId: "",
+ history: ["/%62log/post/caf%C3%A9"],
+ })
+ );
+ selectPage("dynamicId");
+
+ expect($currentSystem.get().params).toEqual({ slug: "café" });
+});
diff --git a/apps/builder/app/shared/system.ts b/apps/builder/app/shared/system.ts
index aa818d88f4..9ebc5434d9 100644
--- a/apps/builder/app/shared/system.ts
+++ b/apps/builder/app/shared/system.ts
@@ -2,9 +2,10 @@ import { atom, computed } from "nanostores";
import { getPagePath, isPage, type Page, type System } from "@webstudio-is/sdk";
import {
compilePathnamePattern,
- matchUrlPattern,
tokenizePathnamePattern,
} from "@webstudio-is/project-build/runtime";
+import { matchPathnamePattern } from "@webstudio-is/wsauth";
+import { toWebstudioParams } from "@webstudio-is/react-sdk";
import { $selectedPage } from "./nano-states/pages";
import { $pages } from "./sync/data-stores";
import { $publishedOrigin } from "./nano-states/misc";
@@ -24,10 +25,18 @@ const extractParams = (
// try to match the first item in history to let user
// see the page without manually entering params
// or selecting them in address bar
- const matchedParams = path
- ? (matchUrlPattern(pattern, path) ??
- (fallbackPattern ? matchUrlPattern(fallbackPattern, path) : undefined))
- : undefined;
+ let matchedParams: System["params"] | undefined;
+ if (path) {
+ const match = matchPathnamePattern(pattern, path);
+ if (match) {
+ matchedParams = toWebstudioParams(pattern, match);
+ } else if (fallbackPattern) {
+ const fallbackMatch = matchPathnamePattern(fallbackPattern, path);
+ if (fallbackMatch) {
+ matchedParams = toWebstudioParams(fallbackPattern, fallbackMatch);
+ }
+ }
+ }
for (const token of tokens) {
if (token.type === "param") {
params[token.name] = matchedParams?.[token.name] ?? undefined;
diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md
index 6ea74067cc..db1fe25e3d 100644
--- a/docs/SUMMARY.md
+++ b/docs/SUMMARY.md
@@ -48,6 +48,8 @@
* [📄 Page settings](university/foundations/page-settings.md)
* [📄 Page templates](university/foundations/page-templates.md)
* [⚙️ Project settings](university/foundations/project-settings.md)
+ * [🌐 HTTP response headers](university/foundations/response-headers.md)
+ * [🔀 Path patterns](university/foundations/path-patterns.md)
* [🎭 Modes](university/foundations/modes.md)
* [🔗 Share links](university/foundations/share-links.md)
* [🌐 Publishing & custom domains](university/foundations/publishing-and-custom-domains.md)
diff --git a/docs/university/foundations/cms.md b/docs/university/foundations/cms.md
index 770b9b9865..8c5071b824 100644
--- a/docs/university/foundations/cms.md
+++ b/docs/university/foundations/cms.md
@@ -44,7 +44,7 @@ Similar to a static page, the path includes dynamic parameters, like a post slug
Adding parameters to a page path will automatically turn the page into a Dynamic Page.
-The path can include dynamic parameters like `:name`, which could be made optional using `:name?`, or have a wildcard such as `/*` or `/:name*` to store the whole remaining part at the end of the URL.
+Use a [path pattern](path-patterns.md) to define which URLs use the Dynamic Page. For example, `/post/:slug` provides the value of `slug` from the URL.
The value of the parameter comes from whatever is in the URL. If the path is `/post/:slug` and somebody views `/post/hello-world` then `hello-world` is the value used in your Resource.
diff --git a/docs/university/foundations/page-settings.md b/docs/university/foundations/page-settings.md
index 8e4636d0fc..9718c9eab6 100644
--- a/docs/university/foundations/page-settings.md
+++ b/docs/university/foundations/page-settings.md
@@ -46,23 +46,9 @@ The URL path for this page, e.g. `/about` or `/blog/:slug`.
### Path syntax
-Webstudio paths can be static or dynamic. Dynamic segments use a `:` prefix, making the page a [Dynamic Page](cms.md#dynamic-pages).
+See [Path patterns](path-patterns.md#pattern-syntax) for static paths, dynamic segments, optional segments, wildcards, and matching examples. A dynamic segment such as `:slug` makes the page a [Dynamic Page](cms.md#dynamic-pages).
-| Pattern | Matches |
-| --- | --- |
-| `/about` | One static route |
-| `/blog/:slug` | One dynamic segment |
-| `/blog/:slug?` | Optional dynamic segment |
-| `/docs/*` | Everything under `/docs/` |
-| `/docs/:path*` | Named wildcard under `/docs/` |
-
-Path rules:
-
-- Paths must start with `/`, except the home page path, which is empty
-- Paths cannot contain repeating `/`
-- Paths cannot end with `/`, except the home route `/`
-- Wildcards such as `*` and `:path*` must be the final segment
-- Parameter names can contain letters, numbers, and underscores
+In Page settings, the home page has an empty path. Other page paths start with `/`.
Webstudio Cloud sites and exported JavaScript applications permanently redirect
a trailing-slash URL such as `/about/` to the page path `/about` and preserve
diff --git a/docs/university/foundations/path-patterns.md b/docs/university/foundations/path-patterns.md
new file mode 100644
index 0000000000..b3fcd7416f
--- /dev/null
+++ b/docs/university/foundations/path-patterns.md
@@ -0,0 +1,63 @@
+---
+description: Define page paths and target project-level Authentication and HTTP response header rules.
+---
+
+# Path patterns
+
+Webstudio uses path patterns to define page URLs and to target project-level **Authentication** and **HTTP response header** rules. These settings share named parameters, optional named parameters, and trailing wildcards. Page paths and project rules differ in which literal characters they accept.
+
+Page settings and project-level rules validate and store paths separately, but use the same router for matching on published dynamic sites. Webstudio generates Remix routes from page paths and uses the underlying React Router matcher for Authentication and Headers rules. A static export has no app router; URL resolution depends on the hosting platform.
+
+## Pattern syntax
+
+Path patterns are slash-separated URL path segments. A segment can be a literal path name, a named parameter, an optional parameter, or a wildcard.
+
+| Pattern | Meaning | Examples that match |
+| --- | --- | --- |
+| `/about` | Exact static path | `/about` |
+| `/blog/:slug` | One required path segment named `slug` | `/blog/hello-world` |
+| `/blog/:slug?` | One optional path segment named `slug` | `/blog`, `/blog/hello-world` |
+| `/docs/*` | `/docs` and any number of path segments below it | `/docs`, `/docs/setup`, `/docs/api/v1` |
+| `/files/:path*` | `/files` and any number of path segments below it | `/files`, `/files/image.png`, `/files/a/b.txt` |
+| `/*` | Any path on the site, including the home page | `/`, `/about`, `/blog/post` |
+| `/` | The home page only | `/` |
+
+Use `:name` for a single segment, `:name?` for one optional segment, and `:name*` for a wildcard matching the remaining path. Parameter names use letters, numbers, and underscores. A parameter must occupy a complete segment; `*` and `:name*` must be the final segment. A literal segment cannot be optional: use `/:lang?/about` to make a segment optional, not `/en?/about`.
+
+Non-root project rules and non-home page paths at the site root start with `/`. Neither accepts repeating slashes such as `//` or a trailing `/`. The project-rule pattern for the home page is `/`; [Page settings](page-settings.md#path) stores the home page path as an empty value. A page inside a folder can also have an empty local path to use that folder's URL. Wildcards must be the final segment.
+
+**Page settings** accepts lowercase letters and digits with the path syntax shown above. It rejects uppercase letters and percent-encoded paths.
+
+**Project settings** accepts a wider range of literal characters. Use `?` only for an optional named parameter. URL-encoded `:`, `*`, and `?` are literal characters, not pattern syntax. For example, `/%2A` matches only that encoded pathname, with the same hex-letter case; it does not match every page.
+
+## Matching behavior in Project settings
+
+Project-level Authentication and Headers compare patterns against the URL pathname. The query string and fragment are not part of the match: `/docs?lang=en#start` is matched as `/docs`.
+
+- Matching is case-insensitive: `/Docs` also matches `/docs`.
+- A trailing slash is ignored for matching: `/about` matches both `/about` and `/about/`.
+- A wildcard matches zero or more trailing segments. Therefore, `/docs/*` matches `/docs` as well as `/docs/setup`.
+- A named wildcard works the same way for matching: `/files/:path*` matches `/files` and paths below it.
+- An optional parameter matches either with or without that one segment: `/blog/:slug?` matches `/blog` and `/blog/post`, but not `/blog/post/comments`.
+- A regular named parameter matches exactly one segment: `/blog/:slug` matches `/blog/post`, but not `/blog` or `/blog/post/comments`.
+- A static path matches only that path: `/about` does not match `/about/team`.
+
+When writing Authentication and Headers rules, use these examples to check the scope before publishing. A pattern such as `/*` is site-wide; `/` is only the home page.
+
+## Page paths on the published site
+
+Page Settings paths become routes in the generated Remix app. For example, Webstudio maps a dynamic segment such as `:slug` to a Remix dynamic route and a trailing `*` to a Remix splat route. Builder navigation and project rules now use the same router matching behavior. A rule for `/docs/*` matches `/docs` and paths below it in both places.
+
+Page routes can provide parameter values to dynamic pages. Authentication and Headers use their patterns only to decide whether a rule applies; they do not expose route parameters. If several rules match, Authentication uses the first matching rule, while Headers applies each matching rule in order. For static exports, the hosting platform determines how page paths resolve.
+
+## Choose a pattern
+
+Start with the narrowest path that covers the pages you intend to affect:
+
+- Use an exact path such as `/campaigns/spring` to target one page.
+- Use a named parameter such as `/blog/:slug` when one segment can vary.
+- Use an optional parameter such as `/blog/:slug?` when the segment may be absent.
+- Use a wildcard such as `/docs/*` when a path and its descendants should share a rule.
+- Use `/*` only when the rule should apply across the whole site.
+
+For example, an Authentication rule for `/private/*` protects `/private` and paths beneath it. A Headers rule for `/campaigns/:slug` applies to each campaign page with one path segment after `/campaigns`.
diff --git a/docs/university/foundations/project-settings.md b/docs/university/foundations/project-settings.md
index 5115d9c841..b48c1f841c 100644
--- a/docs/university/foundations/project-settings.md
+++ b/docs/university/foundations/project-settings.md
@@ -117,7 +117,7 @@ To add a protected route:
4. Click **Add**
5. Publish the site
-Routes use the same syntax as page paths. See [Path syntax](page-settings.md#path-syntax) for supported static routes, dynamic segments, optional segments, and wildcards.
+Routes use the shared [path pattern syntax](path-patterns.md). The guide explains how static paths, parameters, and wildcards match URLs.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../../.gitbook/assets/project-settings-authentication-dark.png">
@@ -146,25 +146,7 @@ For a single page, you can also configure authentication directly in [Page setti
## Headers
-Use **Project settings > Headers** to configure your site's HTTP security response headers. Each header starts with a default value:
-
-| Header | Default | Required |
-| --- | --- | --- |
-| Content-Security-Policy | `frame-ancestors 'self'` | Yes |
-| X-Frame-Options | `SAMEORIGIN` | No |
-| X-Content-Type-Options | `nosniff` | Yes |
-| Referrer-Policy | `strict-origin-when-cross-origin` | Yes |
-| Strict-Transport-Security | `max-age=63072000; includeSubDomains; preload` | Yes |
-
-Edit values directly in their fields. Changes are saved when you leave a field or press Enter; Escape cancels an unsaved edit. Required headers cannot be removed or left empty. Use the trash icon to remove X-Frame-Options and the reset icon to restore a header’s default value. Publish to apply changes.
-
-On Webstudio Cloud, changing the defaults or removing an optional header requires Pro when publishing to a custom domain. Default values and staging are free. Platform headers such as `X-Powered-By` are not configurable.
-
-To allow embedding by `https://example.com`, change Content-Security-Policy to `frame-ancestors 'self' https://example.com` and remove X-Frame-Options.
-
-These are standard HTTP headers. Webstudio Cloud applies the settings automatically to site responses, including redirects and site errors. Static assets served by the CDN keep their existing headers. On other hosts, your server or hosting adapter must apply the configuration generated by the CLI in `app/__generated__/$resources.headers.server.ts`, and any proxy or CDN must preserve the resulting headers. Other hosting templates and static exports do not apply these settings automatically.
-
-Header names are case-insensitive. Each header can be configured once, with values up to 8 KB and a combined limit of 16 KB. Values cannot contain line breaks. Arbitrary headers, including cache directives and cookies, cannot be configured in these settings.
+Configure [HTTP response headers](response-headers.md) to set browser and CDN behavior for your published site. You can apply a header to every route or only to matching paths. Webstudio Cloud supplies framing and referrer defaults when you have not set your own values; platform-managed headers cannot be changed here.
## Marketplace
diff --git a/docs/university/foundations/response-headers.md b/docs/university/foundations/response-headers.md
new file mode 100644
index 0000000000..097e3c682f
--- /dev/null
+++ b/docs/university/foundations/response-headers.md
@@ -0,0 +1,80 @@
+---
+description: Configure HTTP response headers and route-specific policies for a published site.
+---
+
+# HTTP response headers
+
+HTTP response headers are metadata sent with a page response. Browsers and other clients use them to decide how to handle the response—for example, whether a page can appear inside an iframe, how to handle referrers, or how long to cache content. Headers are sent by the server; they are different from the visible content on your page and from HTML added to the page's `<head>`.
+
+Use **Project settings > Headers** to add response header rules to your published site.
+
+## Add a header rule
+
+1. Open **Project settings** and select **Headers**.
+2. Enter a path pattern, a header name, and its value.
+3. Select **Add**.
+4. Publish your site for the rule to take effect.
+
+To change a rule, remove it with the trash button and add it again with the updated values.
+
+Header names are case-insensitive. Suggestions in the header-name field are common choices, not a complete allowlist; you can enter other valid header names too. Webstudio reserves platform-managed and connection-specific headers, as well as headers that describe response-body framing, such as `Content-Length` and `Transfer-Encoding`.
+
+## Choose which paths receive a header
+
+The path pattern determines which page responses receive the rule. Headers use the same path pattern syntax as project-level Authentication. See [Path patterns](path-patterns.md) for the complete syntax, examples, and matching behavior.
+
+Add separate rules to use the same header on different paths. If several matching rules set the same header, the last matching rule in the list wins. A route-specific value replaces the value that would otherwise apply to that response; write the full value you want the browser to receive.
+
+## Webstudio Cloud defaults
+
+On Webstudio Cloud, responses receive these defaults when you have not configured the corresponding header:
+
+| Header | Default value | Purpose |
+| --- | --- | --- |
+| `Content-Security-Policy` | `frame-ancestors 'self'` | Allows pages to be framed by the same site. |
+| `X-Frame-Options` | `SAMEORIGIN` | Legacy framing protection for same-origin embedding. |
+| `Referrer-Policy` | `strict-origin-when-cross-origin` | Limits referrer details sent to another origin. |
+
+`X-Powered-By`, `X-Content-Type-Options`, and `Strict-Transport-Security` are managed by Webstudio Cloud and cannot be configured in this section.
+
+On Webstudio Cloud, the defaults and custom headers on staging domains are free. Custom header rules on a custom domain require Pro.
+
+## Example: allow a trusted site to frame one page
+
+By default, your pages can be framed by your own site. This helps protect visitors from **clickjacking**: an attacker could place your site inside a hidden or misleading frame and trick a visitor into clicking a control on your site without realizing it.
+
+Sometimes a trusted analytics tool offers an iframe-based heatmap viewer. The viewer needs to display your page in a frame so it can place click data over the page. You can allow that viewer while leaving the rest of your site protected:
+
+1. Add a rule for the page you want the viewer to show, for example `/campaigns/spring`.
+2. Set the header name to `Content-Security-Policy`.
+3. Set its value to `frame-ancestors 'self' https://analytics.example.com`, replacing the example origin with the exact origin of the trusted viewer.
+4. Select **Add** and publish.
+
+`frame-ancestors` lists the origins allowed to frame the page. Keep `'self'` if your own site should still be allowed. If the page is nested inside more than one frame, every ancestor must be allowed by the policy. Use a route pattern such as `/*` only when the same embedding rule should apply across the entire site.
+
+Webstudio also sends `X-Frame-Options: SAMEORIGIN` by default. Modern browsers ignore `X-Frame-Options` when an enforced CSP includes `frame-ancestors`, so the explicit CSP rule allows the trusted origin. Older browsers that do not support `frame-ancestors` may still follow `X-Frame-Options` and block external framing. See the [CSP specification](https://www.w3.org/TR/CSP/#frame-ancestors-and-frame-options) and [MDN's `frame-ancestors` reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/frame-ancestors).
+
+## Publish and verify
+
+Publish after adding or changing a rule. Then request the published page and inspect the response headers. For example:
+
+```sh
+curl -sS -D - -o /dev/null https://example.com/campaigns/spring
+```
+
+Check that the response includes the header and value you configured. Use a `GET` request as above; a `HEAD` request may not follow the same response path as a page load.
+
+## Hosting behavior and limits
+
+Webstudio Cloud applies configured headers to site responses, including redirects and site errors. Static assets served by the CDN keep their existing headers.
+
+If you export and host the site elsewhere, configure response headers with your hosting provider. The Headers settings do not automatically configure that host.
+
+You can add up to 100 rules. Header values must be non-empty, cannot contain line breaks or characters outside Latin-1, and can be up to 8 KB; all rules combined are limited to 16 KB. Cookies, connection-specific headers, and response-body framing headers cannot be configured.
+
+## Related
+
+- [Project settings](project-settings.md)
+- [Path patterns](path-patterns.md)
+- [Project settings: Authentication](project-settings.md#authentication)
+- [Publishing & custom domains](publishing-and-custom-domains.md)
diff --git a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx
index fd10aed37e..0ed7374ca3 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/another-page", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx
index 5b804100f8..2a7287b8e9 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
index 9c7d45562e..980e87a3f2 100644
--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsx
index 34b4765781..13c1e1d5b2 100644
--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx
+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx
index fd10aed37e..0ed7374ca3 100644
--- a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/another-page", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/__generated__/_index.server.tsx b/fixtures/react-router-docker/app/__generated__/_index.server.tsx
index 5b804100f8..2a7287b8e9 100644
--- a/fixtures/react-router-docker/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-docker/app/__generated__/_index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
index 9c7d45562e..980e87a3f2 100644
--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsx
index 34b4765781..13c1e1d5b2 100644
--- a/fixtures/react-router-docker/app/routes/_index.tsx
+++ b/fixtures/react-router-docker/app/routes/_index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx
index fd10aed37e..0ed7374ca3 100644
--- a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/another-page", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx b/fixtures/react-router-netlify/app/__generated__/_index.server.tsx
index 5b804100f8..2a7287b8e9 100644
--- a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-netlify/app/__generated__/_index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
index 9c7d45562e..980e87a3f2 100644
--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsx
index 34b4765781..13c1e1d5b2 100644
--- a/fixtures/react-router-netlify/app/routes/_index.tsx
+++ b/fixtures/react-router-netlify/app/routes/_index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx
index fd10aed37e..0ed7374ca3 100644
--- a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/another-page", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx b/fixtures/react-router-vercel/app/__generated__/_index.server.tsx
index 5b804100f8..2a7287b8e9 100644
--- a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx
+++ b/fixtures/react-router-vercel/app/__generated__/_index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
index 9c7d45562e..980e87a3f2 100644
--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsx
index 34b4765781..13c1e1d5b2 100644
--- a/fixtures/react-router-vercel/app/routes/_index.tsx
+++ b/fixtures/react-router-vercel/app/routes/_index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx
index fd10aed37e..0ed7374ca3 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/another-page", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx
index 5b804100f8..2a7287b8e9 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx
index 67acd100fe..95d266a37a 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/redirect", params);
export const contactEmail = undefined;
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx
index 656e3caf0a..7d3a9b8cdc 100644
--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx
+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("", params);
export const contactEmail = undefined;
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx
index fd10aed37e..0ed7374ca3 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/another-page", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx
index 5b804100f8..2a7287b8e9 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx
index 6e96e87093..e3473b5904 100644
--- a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/_route_with_symbols_", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx
index 0bc579460f..410c3018f2 100644
--- a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/animations", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
index 0399a65ed0..913a681030 100644
--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -76,11 +77,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/assets1", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx
index 0bc579460f..fe5e8e181a 100644
--- a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/class-names", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx
index 0bc579460f..f87c231e81 100644
--- a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/content-block", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx
index 11b6af2243..a9bfadaea1 100644
--- a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/duration", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
index 0a87fd66d5..1f31812af5 100644
--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -55,11 +56,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/expressions", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
index d1eefa9929..dec23029cf 100644
--- a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -56,11 +57,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/form", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx
index 0bc579460f..df03dd3aa2 100644
--- a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/head-tag", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx
index 8de563335d..da50f7eaf5 100644
--- a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/heading-with-id", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx
index 21d3998516..5f74b577d8 100644
--- a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/nested-page", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx
index d88577e3cd..5071b62008 100644
--- a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/radix", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
index b3ddec534e..df1455fd9a 100644
--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -55,11 +56,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/resources", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx
index 0bc579460f..9b2661e13f 100644
--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/sitemap.xml", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx
index 11b6af2243..bf92422d37 100644
--- a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -42,11 +43,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("/text-duration", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/__generated__/_index.server.tsx b/fixtures/webstudio-features/app/__generated__/_index.server.tsx
index 4ce2f586aa..f8e810be21 100644
--- a/fixtures/webstudio-features/app/__generated__/_index.server.tsx
+++ b/fixtures/webstudio-features/app/__generated__/_index.server.tsx
@@ -3,6 +3,7 @@
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
import type { System, ResourceRequest } from "@webstudio-is/sdk";
import type { ResourceRequestGraph } from "@webstudio-is/sdk/runtime";
export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {
@@ -46,11 +47,7 @@ export const getResources = (_props: { system: System; resources?: Record<string
};
- type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-
+ export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams("", params);
export const contactEmail = "[email protected]";
\ No newline at end of file
diff --git a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
index 1fb6546d37..51a5601666 100644
--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
index ecc1bccd1f..8b7c39a2ad 100644
--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
index 8e99c349bc..949ace8682 100644
--- a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
index 7f2aa62cd4..a4f111719f 100644
--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
index 1ff50feb37..cf1ded4d38 100644
--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
index 909a6572e8..909e3ae55b 100644
--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
index 226e775b15..f90a9adddc 100644
--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsx
index 5c49542397..d7d07788ff 100644
--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
index ccc195cfb3..b6b524925f 100644
--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
index e1855271c6..1272e7473c 100644
--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
index 602132621b..961336c954 100644
--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
index 1f41b92a9a..a42230882e 100644
--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
index 6ce7f5c574..3463441899 100644
--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
index 49757f0670..5d3782a866 100644
--- a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx
@@ -1,7 +1,7 @@
import { renderToString } from "react-dom/server";
import { type LoaderFunctionArgs, redirect } from "react-router";
import { isLocalResource, loadResources } from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
xmlNodeTagSuffix,
@@ -21,24 +21,6 @@ import { sitemap } from "../__generated__/$resources.sitemap.xml";
import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return fetch(input, init);
@@ -73,7 +55,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
index 53d35450d4..549651834d 100644
--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsx
index 34b4765781..13c1e1d5b2 100644
--- a/fixtures/webstudio-features/app/routes/_index.tsx
+++ b/fixtures/webstudio-features/app/routes/_index.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "../__generated__/$resources.wsauth.server";
import { createGeneratedAssetResourceFetch } from "../__generated__/$resources.asset-query-runtime";
import { assetUrlsByPath } from "../__generated__/$resources.assets";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 1cc22addca..7f0e788daf 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -1823,6 +1823,7 @@ export const prebuild = async (options: {
/* This is a auto generated file for building the project */ \n
import type { PageMeta } from "@webstudio-is/sdk";
+ import { toWebstudioParams } from "@webstudio-is/react-sdk";
${generateResources({
scope,
// XML generation removes the body wrapper from the instance map.
diff --git a/packages/cli/src/response-headers.test.ts b/packages/cli/src/response-headers.test.ts
index cfbe87d8a3..5a34eea169 100644
--- a/packages/cli/src/response-headers.test.ts
+++ b/packages/cli/src/response-headers.test.ts
@@ -21,6 +21,7 @@ test("compiles configured values and route rules as data", () => {
value: "frame-ancestors https://example.com",
},
{ route: "/docs/*", name: "Referrer-Policy", value: "no-referrer" },
+ { route: "/%2A", name: "X-Legacy-Route", value: "literal" },
{ name: "Cache-Control", value: "public, max-age=60" },
];
expect(
diff --git a/packages/cli/templates/react-router/app/route-templates/html.tsx b/packages/cli/templates/react-router/app/route-templates/html.tsx
index 9315a0b938..51fe02d092 100644
--- a/packages/cli/templates/react-router/app/route-templates/html.tsx
+++ b/packages/cli/templates/react-router/app/route-templates/html.tsx
@@ -18,7 +18,7 @@ import {
formBotFieldName,
cachedFetch,
} from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
PageSettingsMeta,
@@ -47,24 +47,6 @@ import { authRoutes } from "__AUTH__";
import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
import { assetUrlsByPath } from "__ASSETS__";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return cachedFetch(projectId, input, init);
@@ -99,7 +81,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
@@ -259,7 +245,7 @@ export const action = async ({
}: ActionFunctionArgs): Promise<
{ success: true } | { success: false; errors: string[] }
> => {
- authenticateProductionRequest(request);
+ authenticateProjectRequest(request, authRoutes, projectDomain);
try {
const url = new URL(request.url);
diff --git a/packages/cli/templates/react-router/app/route-templates/text.tsx b/packages/cli/templates/react-router/app/route-templates/text.tsx
index 637ae82b41..4c93bf0223 100644
--- a/packages/cli/templates/react-router/app/route-templates/text.tsx
+++ b/packages/cli/templates/react-router/app/route-templates/text.tsx
@@ -1,30 +1,12 @@
import { type LoaderFunctionArgs, redirect } from "react-router";
import { isLocalResource, loadResources } from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import { projectDomain } from "__CLIENT__";
import { getPageMeta, getRemixParams, getResources } from "__SERVER__";
import { sitemap } from "__SITEMAP__";
import { authRoutes } from "__AUTH__";
import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return fetch(input, init);
@@ -57,7 +39,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
diff --git a/packages/cli/templates/react-router/app/route-templates/xml.tsx b/packages/cli/templates/react-router/app/route-templates/xml.tsx
index 90d8ec6502..512721b8ad 100644
--- a/packages/cli/templates/react-router/app/route-templates/xml.tsx
+++ b/packages/cli/templates/react-router/app/route-templates/xml.tsx
@@ -1,7 +1,7 @@
import { renderToString } from "react-dom/server";
import { type LoaderFunctionArgs, redirect } from "react-router";
import { isLocalResource, loadResources } from "@webstudio-is/sdk/runtime";
-import { authenticateRequest } from "@webstudio-is/wsauth";
+import { authenticateProjectRequest } from "@webstudio-is/wsauth";
import {
ReactSdkContext,
xmlNodeTagSuffix,
@@ -13,24 +13,6 @@ import { sitemap } from "__SITEMAP__";
import { authRoutes } from "__AUTH__";
import { createGeneratedAssetResourceFetch } from "__ASSET_QUERY_RUNTIME__";
-const authenticateProductionRequest = (request: Request) => {
- const host =
- request.headers.get("x-forwarded-host") ||
- request.headers.get("host") ||
- "";
-
- const requestHost = host.split(":")[0];
- if (
- projectDomain !== undefined &&
- (requestHost === projectDomain ||
- requestHost.startsWith(`${projectDomain}.`))
- ) {
- return;
- }
-
- return authenticateRequest(request, authRoutes);
-};
-
const customFetch: typeof fetch = (input, init) => {
if (typeof input !== "string") {
return fetch(input, init);
@@ -65,7 +47,11 @@ const customFetch: typeof fetch = (input, init) => {
};
export const loader = async (arg: LoaderFunctionArgs) => {
- const authRoute = authenticateProductionRequest(arg.request);
+ const authRoute = authenticateProjectRequest(
+ arg.request,
+ authRoutes,
+ projectDomain
+ );
const url = new URL(arg.request.url);
const host =
diff --git a/packages/project-build/src/runtime/pages.test.ts b/packages/project-build/src/runtime/pages.test.ts
index 4bcdb9348b..eb412bcdb6 100644
--- a/packages/project-build/src/runtime/pages.test.ts
+++ b/packages/project-build/src/runtime/pages.test.ts
@@ -834,6 +834,70 @@ describe("serialized page helpers", () => {
});
});
+ test("looks up pages with published route ranking and wildcard behavior", () => {
+ const pages = migratePages({
+ meta: {},
+ homePage: {
+ id: "home",
+ name: "Home",
+ path: "",
+ title: `"Home"`,
+ meta: {},
+ rootInstanceId: "homeBody",
+ },
+ pages: [
+ {
+ id: "docs-splat",
+ name: "Docs splat",
+ path: "/docs/*",
+ title: `"Docs splat"`,
+ meta: {},
+ rootInstanceId: "docsSplatBody",
+ },
+ {
+ id: "docs-optional",
+ name: "Docs optional",
+ path: "/docs/:slug?",
+ title: `"Docs optional"`,
+ meta: {},
+ rootInstanceId: "docsOptionalBody",
+ },
+ {
+ id: "docs-static",
+ name: "Docs static",
+ path: "/docs/guide",
+ title: `"Docs static"`,
+ meta: {},
+ rootInstanceId: "docsStaticBody",
+ },
+ ],
+ folders: [
+ createRootFolder([
+ "home",
+ "docs-splat",
+ "docs-optional",
+ "docs-static",
+ ]),
+ ],
+ });
+ const serializedPages = getSerializedPages({ pages });
+
+ for (const [path, expectedPageId] of [
+ ["/docs", "docs-optional"],
+ ["/docs/guide", "docs-static"],
+ ["/docs/other", "docs-optional"],
+ ["/docs/a/b", "docs-splat"],
+ ["/DOCS/GUIDE", "docs-static"],
+ ]) {
+ expect(
+ findSerializedPageByInput(serializedPages, { pagePath: path })?.id
+ ).toBe(expectedPageId);
+ }
+ expect(
+ findSerializedPageByInput(serializedPages, { pagePath: "/docs/*" })?.id
+ ).toBe("docs-splat");
+ });
+
test("serializes page summary and details with parent folder", () => {
const pages = createDefaultPages({
rootInstanceId: "root",
diff --git a/packages/project-build/src/runtime/pages.ts b/packages/project-build/src/runtime/pages.ts
index cb3987b1a2..6c4479fd8a 100644
--- a/packages/project-build/src/runtime/pages.ts
+++ b/packages/project-build/src/runtime/pages.ts
@@ -27,6 +27,7 @@ import { serializePages } from "@webstudio-is/project-migrations/pages";
import * as bcp47 from "bcp-47";
import slugify from "slugify";
import { z } from "zod";
+import { matchPathnameRoutes } from "@webstudio-is/wsauth";
import {
compactBuilderPatchPayload,
type BuilderPatchChange,
@@ -151,40 +152,17 @@ export const getSerializedPagePath = (
export const normalizeSerializedPagePath = (path: string) =>
path === "/" ? "" : path;
-const escapeRegExp = (value: string) =>
- value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-
-const isSerializedPagePathMatch = (pattern: string, path: string) => {
- if (pattern === path) {
- return true;
- }
- const segments = pattern.split("/");
- const pathSegments = path.split("/");
- const regexParts = segments.map((segment, index) => {
- if (segment === "*") {
- return index === segments.length - 1 ? ".*" : "[^/]+";
- }
- const param = segment.match(/^:(\w+)([?*]?)$/);
- if (param === null) {
- return escapeRegExp(segment);
- }
- const modifier = param[2];
- if (modifier === "?") {
- return "[^/]*";
- }
- if (modifier === "*") {
- return index === segments.length - 1 ? ".*" : "[^/]+";
- }
- return "[^/]+";
- });
- if (
- segments.length !== pathSegments.length &&
- pattern.endsWith("*") === false
- ) {
- return false;
- }
- return new RegExp(`^${regexParts.join("/")}$`).test(path);
-};
+const findMatchingSerializedPageByPath = (
+ pages: SerializedPages,
+ path: string
+) =>
+ matchPathnameRoutes(
+ pages.pages.map((page) => ({
+ pattern: getSerializedPagePath(pages, page),
+ value: page,
+ })),
+ normalizeSerializedPagePath(path)
+ )?.value;
export const serializePageSummary = (
pages: SerializedPages,
@@ -236,12 +214,7 @@ export const findSerializedPageByInput = (
const exactPage = pages.pages.find(
(page) => getSerializedPagePath(pages, page) === pagePath
);
- return (
- exactPage ??
- pages.pages.find((page) =>
- isSerializedPagePathMatch(getSerializedPagePath(pages, page), pagePath)
- )
- );
+ return exactPage ?? findMatchingSerializedPageByPath(pages, pagePath);
}
};
@@ -255,16 +228,6 @@ const findExactSerializedPageByPath = (
);
};
-const findMatchingSerializedPageByPath = (
- pages: SerializedPages,
- path: string
-) => {
- const pagePath = normalizeSerializedPagePath(path);
- return pages.pages.find((page) =>
- isSerializedPagePathMatch(getSerializedPagePath(pages, page), pagePath)
- );
-};
-
const isSerializedFallbackPage = (
pages: SerializedPages,
page: SerializedPage
diff --git a/packages/project-build/src/runtime/redirect-source.test.ts b/packages/project-build/src/runtime/redirect-source.test.ts
index 8f18660f34..084a1bf44d 100644
--- a/packages/project-build/src/runtime/redirect-source.test.ts
+++ b/packages/project-build/src/runtime/redirect-source.test.ts
@@ -71,6 +71,23 @@ describe("redirect source helpers", () => {
false
);
});
+
+ test.each([
+ ["/docs/*", "/docs", true],
+ ["/docs/*", "/docs/setup", true],
+ ["/docs/*", "/docs123", false],
+ ["/docs/:rest*", "/docs", true],
+ ["/docs/:rest*", "/docs/setup/one", true],
+ ["/Docs/:slug", "/docs/%64emo", true],
+ ["/docs/:slug", "/docs", false],
+ ["/docs/:slug?", "/docs", true],
+ ["/docs/:slug?", "/docs/a/b", false],
+ ] as const)(
+ "matches redirect source %s against local URL %s: %s",
+ (source, url, expected) => {
+ expect(doesRedirectSourceMatchLocalUrl(source, url)).toBe(expected);
+ }
+ );
});
describe("findMatchingRedirect", () => {
@@ -259,6 +276,16 @@ describe("doesRedirectSourceOverridePagePath", () => {
);
});
+ test("recognizes a redirect splat at its base page path", () => {
+ expect(doesRedirectSourceOverridePagePath("/docs/*", "/docs")).toBe(true);
+ expect(doesRedirectSourceOverridePagePath("/docs/:rest*", "/docs")).toBe(
+ true
+ );
+ expect(doesRedirectSourceOverridePagePath("/docs/*", "/docs-other")).toBe(
+ false
+ );
+ });
+
test("returns false for exact-query redirect source", () => {
expect(doesRedirectSourceOverridePagePath("/about?x=1", "/about")).toBe(
false
diff --git a/packages/project-build/src/runtime/redirect-source.ts b/packages/project-build/src/runtime/redirect-source.ts
index d8f79881e1..f812ec10c2 100644
--- a/packages/project-build/src/runtime/redirect-source.ts
+++ b/packages/project-build/src/runtime/redirect-source.ts
@@ -1,4 +1,4 @@
-import { matchUrlPattern } from "./url-pattern";
+import { matchPathnamePattern } from "@webstudio-is/wsauth";
const isOptionalSegmentMarker = (source: string, index: number) => {
const nextChar = source[index + 1];
@@ -179,7 +179,7 @@ const getOptionalStaticSegmentVariants = (pathname: string) => {
const doesPathnamePatternOverlap = (pattern: string, pathname: string) => {
for (const patternVariant of getOptionalStaticSegmentVariants(pattern)) {
for (const pathnameVariant of getOptionalStaticSegmentVariants(pathname)) {
- if (matchUrlPattern(patternVariant, pathnameVariant) !== undefined) {
+ if (matchPathnamePattern(patternVariant, pathnameVariant) !== undefined) {
return true;
}
}
@@ -203,18 +203,7 @@ export const doesRedirectSourceMatchLocalUrl = (
}
const normalizedUrlPathname = getRedirectSourcePathname(normalizedUrl);
- for (const sourceVariant of getOptionalStaticSegmentVariants(
- normalizedSource
- )) {
- for (const urlVariant of getOptionalStaticSegmentVariants(
- normalizedUrlPathname
- )) {
- if (matchUrlPattern(sourceVariant, urlVariant) !== undefined) {
- return true;
- }
- }
- }
- return false;
+ return doesPathnamePatternOverlap(normalizedSource, normalizedUrlPathname);
};
export const doesRedirectSourceOverridePagePath = (
diff --git a/packages/project-build/src/runtime/url-pattern.test.ts b/packages/project-build/src/runtime/url-pattern.test.ts
index a2bdb1a251..3ae166af6b 100644
--- a/packages/project-build/src/runtime/url-pattern.test.ts
+++ b/packages/project-build/src/runtime/url-pattern.test.ts
@@ -1,24 +1,31 @@
+import { matchPathnamePattern as matchRouterPattern } from "@webstudio-is/wsauth";
+import { toWebstudioParams } from "@webstudio-is/react-sdk";
import { expect, test, describe } from "vitest";
import {
compilePathnamePattern,
isPathnamePattern,
- matchUrlPattern,
tokenizePathnamePattern,
validatePathnamePattern,
} from "./url-pattern";
import { VALID_URLPATTERN_PATHS } from "@webstudio-is/sdk/router-path-test-data";
+// Published pages adapt Remix's "*" parameter to Webstudio's page path names.
+const matchPathnamePattern = (pattern: string, pathname: string) => {
+ const params = matchRouterPattern(pattern, pathname);
+ return params === undefined ? undefined : toWebstudioParams(pattern, params);
+};
+
/**
* These tests use the shared test data from @webstudio-is/sdk to ensure
- * URLPattern matching is consistent with schema validation.
+ * route matching is consistent with schema validation.
*/
-describe("Shared router path tests - URLPattern matching", () => {
- describe("all valid paths can be used as URLPattern patterns", () => {
+describe("Shared router path tests - published route matching", () => {
+ describe("all valid paths can be used as route patterns", () => {
test.each(VALID_URLPATTERN_PATHS)("accepts pattern: %s", (pattern) => {
- // Pattern should be valid for URLPattern
+ // Pattern should be valid for the published router
// Some patterns may have validation errors due to our custom rules
- // but they should still work with URLPattern itself
- expect(() => matchUrlPattern(pattern, pattern)).not.toThrow();
+ // but the matcher must handle them safely
+ expect(() => matchPathnamePattern(pattern, pattern)).not.toThrow();
});
});
@@ -29,94 +36,101 @@ describe("Shared router path tests - URLPattern matching", () => {
);
test.each(staticPaths)("matches exactly: %s", (path) => {
- const result = matchUrlPattern(path, path);
+ const result = matchPathnamePattern(path, path);
expect(result).toEqual({});
});
});
});
test("decode matched params", () => {
- expect(matchUrlPattern("/blog/:slug", "/blog/привет")).toEqual({
+ expect(matchPathnamePattern("/blog/:slug", "/blog/привет")).toEqual({
slug: "привет",
});
expect(
- matchUrlPattern("/blog/:slug", "/blog/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82")
+ matchPathnamePattern(
+ "/blog/:slug",
+ "/blog/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82"
+ )
).toEqual({
slug: "привет",
});
});
-test("URLPattern wildcard requires the slash after its base path", () => {
- expect(matchUrlPattern("/docs/*", "/docs")).toBeUndefined();
- expect(matchUrlPattern("/docs/*", "/docs/")).toEqual({});
+test("published splat matches its base path", () => {
+ expect(matchPathnamePattern("/docs/*", "/docs")).toEqual({ 0: "" });
+ expect(matchPathnamePattern("/docs/*", "/docs/")).toEqual({ 0: "" });
});
-describe("URLPattern Unicode/non-Latin character support", () => {
- // These tests verify that the URLPattern-based router properly handles
+describe("Published router Unicode/non-Latin character support", () => {
+ // These tests verify that the published router matcher properly handles
// non-Latin characters in redirect paths, which is important for
// international websites (Chinese, Japanese, Korean, etc.)
describe("exact path matching with non-Latin characters", () => {
test("matches Chinese Simplified paths", () => {
- expect(matchUrlPattern("/关于我们", "/关于我们")).toEqual({});
- expect(matchUrlPattern("/产品/手机", "/产品/手机")).toEqual({});
+ expect(matchPathnamePattern("/关于我们", "/关于我们")).toEqual({});
+ expect(matchPathnamePattern("/产品/手机", "/产品/手机")).toEqual({});
});
test("matches Chinese Traditional paths", () => {
- expect(matchUrlPattern("/關於我們", "/關於我們")).toEqual({});
- expect(matchUrlPattern("/港聞", "/港聞")).toEqual({});
+ expect(matchPathnamePattern("/關於我們", "/關於我們")).toEqual({});
+ expect(matchPathnamePattern("/港聞", "/港聞")).toEqual({});
});
test("matches Japanese paths (Hiragana, Katakana, Kanji)", () => {
- expect(matchUrlPattern("/こんにちは", "/こんにちは")).toEqual({});
- expect(matchUrlPattern("/カテゴリ", "/カテゴリ")).toEqual({});
- expect(matchUrlPattern("/日本語", "/日本語")).toEqual({});
+ expect(matchPathnamePattern("/こんにちは", "/こんにちは")).toEqual({});
+ expect(matchPathnamePattern("/カテゴリ", "/カテゴリ")).toEqual({});
+ expect(matchPathnamePattern("/日本語", "/日本語")).toEqual({});
});
test("matches Korean paths (Hangul)", () => {
- expect(matchUrlPattern("/한국어", "/한국어")).toEqual({});
- expect(matchUrlPattern("/블로그/포스트", "/블로그/포스트")).toEqual({});
+ expect(matchPathnamePattern("/한국어", "/한국어")).toEqual({});
+ expect(matchPathnamePattern("/블로그/포스트", "/블로그/포스트")).toEqual(
+ {}
+ );
});
test("matches Cyrillic paths", () => {
- expect(matchUrlPattern("/о-нас", "/о-нас")).toEqual({});
- expect(matchUrlPattern("/блог/статья", "/блог/статья")).toEqual({});
+ expect(matchPathnamePattern("/о-нас", "/о-нас")).toEqual({});
+ expect(matchPathnamePattern("/блог/статья", "/блог/статья")).toEqual({});
});
test("matches Arabic paths", () => {
- expect(matchUrlPattern("/مرحبا", "/مرحبا")).toEqual({});
+ expect(matchPathnamePattern("/مرحبا", "/مرحبا")).toEqual({});
});
test("matches Hebrew paths", () => {
- expect(matchUrlPattern("/שלום", "/שלום")).toEqual({});
+ expect(matchPathnamePattern("/שלום", "/שלום")).toEqual({});
});
test("matches Greek paths", () => {
- expect(matchUrlPattern("/σχετικά", "/σχετικά")).toEqual({});
+ expect(matchPathnamePattern("/σχετικά", "/σχετικά")).toEqual({});
});
test("matches European diacritics", () => {
- expect(matchUrlPattern("/über-uns", "/über-uns")).toEqual({});
- expect(matchUrlPattern("/café", "/café")).toEqual({});
- expect(matchUrlPattern("/niño", "/niño")).toEqual({});
+ expect(matchPathnamePattern("/über-uns", "/über-uns")).toEqual({});
+ expect(matchPathnamePattern("/café", "/café")).toEqual({});
+ expect(matchPathnamePattern("/niño", "/niño")).toEqual({});
});
});
describe("dynamic segments with non-Latin characters", () => {
test("captures Chinese characters in :slug parameter", () => {
- expect(matchUrlPattern("/:slug", "/关于我们")).toEqual({
+ expect(matchPathnamePattern("/:slug", "/关于我们")).toEqual({
slug: "关于我们",
});
});
test("captures Japanese characters in :slug parameter", () => {
- expect(matchUrlPattern("/blog/:slug", "/blog/日本語")).toEqual({
+ expect(matchPathnamePattern("/blog/:slug", "/blog/日本語")).toEqual({
slug: "日本語",
});
});
test("captures Korean characters in :slug parameter", () => {
- expect(matchUrlPattern("/:category/:post", "/블로그/포스트")).toEqual({
+ expect(
+ matchPathnamePattern("/:category/:post", "/블로그/포스트")
+ ).toEqual({
category: "블로그",
post: "포스트",
});
@@ -125,13 +139,15 @@ describe("URLPattern Unicode/non-Latin character support", () => {
describe("wildcard patterns with non-Latin characters", () => {
test("matches wildcard with Chinese paths", () => {
- expect(matchUrlPattern("/blog/*", "/blog/中文/测试")).toEqual({
+ expect(matchPathnamePattern("/blog/*", "/blog/中文/测试")).toEqual({
0: "中文/测试",
});
});
test("matches wildcard with Japanese paths", () => {
- expect(matchUrlPattern("/カテゴリ/*", "/カテゴリ/記事/詳細")).toEqual({
+ expect(
+ matchPathnamePattern("/カテゴリ/*", "/カテゴリ/記事/詳細")
+ ).toEqual({
0: "記事/詳細",
});
});
@@ -140,14 +156,14 @@ describe("URLPattern Unicode/non-Latin character support", () => {
describe("URL-encoded vs literal matching", () => {
test("matches URL-encoded paths and decodes them", () => {
// %E6%B8%AF%E8%81%9E is URL-encoded 港聞
- expect(matchUrlPattern("/:slug", "/%E6%B8%AF%E8%81%9E")).toEqual({
+ expect(matchPathnamePattern("/:slug", "/%E6%B8%AF%E8%81%9E")).toEqual({
slug: "港聞",
});
});
test("matches mixed Latin and non-Latin paths", () => {
- expect(matchUrlPattern("/blog/关于", "/blog/关于")).toEqual({});
- expect(matchUrlPattern("/news/:slug", "/news/港聞")).toEqual({
+ expect(matchPathnamePattern("/blog/关于", "/blog/关于")).toEqual({});
+ expect(matchPathnamePattern("/news/:slug", "/news/港聞")).toEqual({
slug: "港聞",
});
});
diff --git a/packages/project-build/src/runtime/url-pattern.ts b/packages/project-build/src/runtime/url-pattern.ts
index ec50daf005..999004fd97 100644
--- a/packages/project-build/src/runtime/url-pattern.ts
+++ b/packages/project-build/src/runtime/url-pattern.ts
@@ -5,37 +5,6 @@ export { isPathnamePattern };
const baseUrl = "http://url";
-const tryDecode = (encoded: string) => {
- try {
- return decodeURIComponent(encoded);
- } catch {
- return encoded;
- }
-};
-
-/**
- * Match a page or redirect path using URLPattern. Returns decoded parameters
- * (`{}` for a static match) or `undefined` when it does not match. Unlike the
- * wsauth's `matchesPathnamePattern`, `/docs/*` does not match `/docs` here.
- */
-export const matchUrlPattern = (pattern: string, pathname: string) => {
- try {
- const groups = new URLPattern({ pathname: pattern }).exec({ pathname })
- ?.pathname.groups;
- if (groups) {
- const decodedGroups: Record<string, undefined | string> = {};
- for (const [name, value] of Object.entries(groups)) {
- if (value) {
- decodedGroups[name] = tryDecode(value);
- }
- }
- return decodedGroups;
- }
- } catch {
- // Invalid URLPattern syntax never matches.
- }
-};
-
// allowed syntax
// :name - group without modifiers
// :name? - group with optional modifier
diff --git a/packages/react-sdk/src/remix.test.ts b/packages/react-sdk/src/remix.test.ts
index 869c85140b..d141388fc9 100644
--- a/packages/react-sdk/src/remix.test.ts
+++ b/packages/react-sdk/src/remix.test.ts
@@ -1,5 +1,9 @@
import { expect, test, describe } from "vitest";
-import { generateRemixParams, generateRemixRoute } from "./remix";
+import {
+ generateRemixParams,
+ generateRemixRoute,
+ toWebstudioParams,
+} from "./remix";
import { STATIC_PATHS } from "@webstudio-is/sdk/router-path-test-data";
/**
@@ -87,33 +91,20 @@ test("convert named groups to remix route", () => {
);
});
-test("generate remix params for static pathname", () => {
- expect("\n" + generateRemixParams("/blog/my-post")).toEqual(`
-type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- return params
-}
-`);
-});
-
-test("generate remix params converter with wildcard", () => {
- expect("\n" + generateRemixParams("/blog/*")).toEqual(`
-type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- params[0] = params["*"]
- delete params["*"]
- return params
-}
-`);
+test("maps Remix splats to Webstudio page parameter names", () => {
+ expect(toWebstudioParams("/blog/:name*", { "*": "a/b" })).toEqual({
+ name: "a/b",
+ });
+ expect(toWebstudioParams("/blog/*", { "*": "a/b" })).toEqual({
+ 0: "a/b",
+ });
+ expect(toWebstudioParams("/blog/:slug", { slug: "post" })).toEqual({
+ slug: "post",
+ });
});
-test("generate remix params converter with named group and * modifier", () => {
- expect("\n" + generateRemixParams("/blog/:name*")).toEqual(`
-type Params = Record<string, string | undefined>;
-export const getRemixParams = ({ ...params }: Params): Params => {
- params["name"] = params["*"]
- delete params["*"]
- return params
-}
-`);
+test("generated pages call the shared parameter adapter", () => {
+ expect(generateRemixParams("/docs/:rest*")).toContain(
+ 'toWebstudioParams("/docs/:rest*", params)'
+ );
});
diff --git a/packages/react-sdk/src/remix.ts b/packages/react-sdk/src/remix.ts
index 6cf4f9ae86..2ff7ef6d96 100644
--- a/packages/react-sdk/src/remix.ts
+++ b/packages/react-sdk/src/remix.ts
@@ -42,29 +42,23 @@ export const generateRemixRoute = (pathname: string) => {
return `${base}${tail}`;
};
-/**
- * generates a function to convert remix params to compatible with url pattern groups
- *
- * for /:name* pattern
- * params["*"] is replaced with params["name"]
- *
- * for /* pattern
- * params["*"] is replaced with params[0]
- */
-export const generateRemixParams = (pathname: string) => {
- const name = pathname.match(/:(?<name>\w+)\*$/)?.groups?.name;
- let generated = "";
- generated += `type Params = Record<string, string | undefined>;\n`;
- generated += `export const getRemixParams = ({ ...params }: Params): Params => {\n`;
- if (name) {
- generated += ` params["${name}"] = params["*"]\n`;
- generated += ` delete params["*"]\n`;
- }
- if (pathname.endsWith("/*")) {
- generated += ` params[0] = params["*"]\n`;
- generated += ` delete params["*"]\n`;
+/** Map Remix splat parameters to the names used in Webstudio page paths. */
+export const toWebstudioParams = (
+ pathname: string,
+ params: Record<string, string | undefined>
+) => {
+ const result = { ...params };
+ const namedSplat = pathname.match(/:(\w+)\*$/)?.[1];
+ if (namedSplat) {
+ result[namedSplat] = result["*"];
+ delete result["*"];
+ } else if (pathname.endsWith("/*")) {
+ result[0] = result["*"];
+ delete result["*"];
}
- generated += ` return params\n`;
- generated += `}\n`;
- return generated;
+ return result;
};
+
+/** Generate the page-specific wrapper used by published routes. */
+export const generateRemixParams = (pathname: string) =>
+ `export const getRemixParams = (params: Record<string, string | undefined>) => toWebstudioParams(${JSON.stringify(pathname)}, params);`;
diff --git a/packages/sdk/src/schema/response-headers.test.ts b/packages/sdk/src/schema/response-headers.test.ts
index df1240946b..a9b65594ef 100644
--- a/packages/sdk/src/schema/response-headers.test.ts
+++ b/packages/sdk/src/schema/response-headers.test.ts
@@ -50,6 +50,14 @@ describe("response header settings", () => {
).toBe(false);
});
+ test("keeps encoded literal routes in saved header rules", () => {
+ expect(
+ customResponseHeaders.safeParse([
+ { route: "/%2A", name: "Referrer-Policy", value: "no-referrer" },
+ ]).success
+ ).toBe(true);
+ });
+
test("edits rules by route and case-insensitive name", () => {
const headers = [
{ name: "Cache-Control", value: "all paths" },
diff --git a/packages/wsauth/README.md b/packages/wsauth/README.md
index aa0575c844..e730da51fd 100644
--- a/packages/wsauth/README.md
+++ b/packages/wsauth/README.md
@@ -37,22 +37,10 @@ Version 1 uses JSON with route strings as keys:
}
```
-Routes use the same path pattern syntax Webstudio uses for pages:
-
-- Static segment: `/about`
-- Named parameter: `/blog/:slug`
-- Optional named parameter: `/blog/:slug?`
-- Wildcard: `/docs/*`
-- Named wildcard: `/docs/:path*`
-
-Route rules:
-
-- A route must start with `/`.
-- A route must not contain repeating `/`.
-- A route must not end with `/`, except the root route `/`.
-- `*` and `:name*` wildcard segments must be the final segment.
-- Named parameters use `:name`, `:name?`, or `:name*`.
-- Parameter names must contain word characters only, matching `\w+`.
+Routes use Webstudio's [path pattern syntax](https://github.com/webstudio-is/webstudio/blob/main/docs/university/foundations/path-patterns.md).
+The guide covers validation, matching, and the differences between page paths
+and project rules. Authentication keeps the first matching rule when several
+rules cover one URL.
## Basic Auth
diff --git a/packages/wsauth/package.json b/packages/wsauth/package.json
index a380afac78..7a82da5598 100644
--- a/packages/wsauth/package.json
+++ b/packages/wsauth/package.json
@@ -12,6 +12,7 @@
"test": "vitest run"
},
"dependencies": {
+ "@remix-run/router": "1.23.0",
"zod": "^4.4.3"
},
"devDependencies": {
diff --git a/packages/wsauth/src/index.test.ts b/packages/wsauth/src/index.test.ts
index 4704de9ec1..820159087a 100644
--- a/packages/wsauth/src/index.test.ts
+++ b/packages/wsauth/src/index.test.ts
@@ -1,13 +1,16 @@
import { describe, expect, test } from "vitest";
import {
+ authenticateProjectRequest,
authenticateRequest,
buildWsAuth,
createBasicAuthRoute,
createWsAuthResources,
findWsAuthRoute,
getBasicAuthCredentials,
- matchesPathnamePattern,
+ matchPathnamePattern,
+ matchPathnameRoutes,
parseWsAuth,
+ parseWsAuthOrThrow,
validateBasicAuth,
validatePathnamePattern,
} from "./index";
@@ -121,15 +124,31 @@ describe("wsauth", () => {
});
});
- test("validates route syntax", () => {
- expect(validatePathnamePattern("/private")).toBeUndefined();
- expect(validatePathnamePattern("/docs/*")).toBeUndefined();
- expect(validatePathnamePattern("private")).toBe(
- 'Route must start with "/"'
- );
- expect(validatePathnamePattern("/docs/*/page")).toBe(
- "Wildcard route segment must be the last segment"
- );
+ test.each([
+ ["/", undefined],
+ ["/private", undefined],
+ ["/static/path", undefined],
+ ["/docs/*", undefined],
+ ["/:id", undefined],
+ ["/:id?", undefined],
+ ["/:path*", undefined],
+ ["/*", undefined],
+ ["private", 'Route must start with "/"'],
+ ["/docs/", 'Route must not end with "/"'],
+ ["/docs//api", 'Route must not contain repeating "/"'],
+ ["/docs/*/api", "Wildcard route segment must be the last segment"],
+ ["/docs/:path*/api", "Wildcard route segment must be the last segment"],
+ ["/docs/:bad-name", 'Invalid route parameter ":bad-name"'],
+ ["/docs/:name??", 'Invalid route parameter ":name??"'],
+ ["/docs/a?", 'Optional marker "?" is only allowed on a named parameter'],
+ ["/docs/a*", "Wildcard can only be used as * or :name*"],
+ ["/%3Aid", undefined],
+ ["/%3F", undefined],
+ ["/%2A", undefined],
+ ["/%252A", undefined],
+ ["/%ZZ", undefined],
+ ] as const)("validates project rule %s", (pattern, error) => {
+ expect(validatePathnamePattern(pattern)).toBe(error);
});
test.each([
@@ -145,11 +164,218 @@ describe("wsauth", () => {
["/docs/:id?", "/docs", true],
["/docs/:id?", "/docs/a", true],
["/docs/:id?", "/docs/a/b", false],
+ ["/docs/:id?", "/docs123", false],
["/docs/:rest*", "/docs/a/b", true],
- ["/Docs", "/docs", false],
+ ["/docs/:rest*", "/docs", true],
+ ["/docs/:rest*", "/docs123", false],
+ ["/docs/*", "/docs123", false],
+ ["/docs/*", "/docs/a/b", true],
+ ["/docs/:id", "/docs/a/b", false],
+ ["/docs/:id", "/docs/", false],
+ ["/docs/:id?", "/docs/", true],
+ ["/Docs", "/docs", true],
["/docs", "/docs/", true],
+ ["/docs", "/docs//", true],
+ ["/docs", "/%64ocs", true],
+ ["/café", "/caf%C3%A9", true],
+ ["/foo%20bar", "/foo%20bar", true],
+ ["/path%2Bplus", "/path%2Bplus", true],
+ ["/files/a%2Fb", "/files/a%2Fb", true],
+ ["/files/a%2Fb", "/files/a/b", false],
+ ["/%ZZ", "/%ZZ", true],
+ ["", "/", true],
] as const)("matches %s against %s: %s", (pattern, pathname, expected) => {
- expect(matchesPathnamePattern(pattern, pathname)).toBe(expected);
+ expect(matchPathnamePattern(pattern, pathname) !== undefined).toBe(
+ expected
+ );
+ });
+
+ test.each([
+ ["/%2A", "/%2A", true],
+ ["/%2A", "/%2a", false],
+ ["/%2A", "/docs", false],
+ ["/%3F", "/%3F", true],
+ ["/%3F", "/", false],
+ ["/%3Aid", "/%3Aid", true],
+ ["/%3Aid", "/docs", false],
+ ["/%252A", "/%252A", true],
+ ["/%252A", "/%2A", false],
+ ["/%ZZ", "/%ZZ", true],
+ ["/docs/%2A", "/docs/%2A", true],
+ ["/docs/%2A", "/docs/guide", false],
+ ] as const)(
+ "does not interpret a saved encoded literal %s as router syntax at %s",
+ (pattern, pathname, expected) => {
+ expect(matchPathnamePattern(pattern, pathname) !== undefined).toBe(
+ expected
+ );
+ }
+ );
+
+ test("ranks saved encoded literals without losing other routes", () => {
+ const routes = [
+ { pattern: "/:id", value: "dynamic" },
+ { pattern: "/%2A", value: "encoded literal" },
+ { pattern: "/docs", value: "docs" },
+ ];
+ expect(matchPathnameRoutes(routes, "/%2A")?.value).toBe("encoded literal");
+ expect(matchPathnameRoutes(routes, "/docs")?.value).toBe("docs");
+ expect(matchPathnameRoutes(routes, "/%2a")?.params).toEqual({ id: "*" });
+ });
+
+ test("restores parameters when another route wins over an encoded literal", () => {
+ const routes = [
+ { pattern: "/%2A/other", value: "encoded literal" },
+ { pattern: "/:id/leaf", value: "dynamic" },
+ ];
+ expect(matchPathnameRoutes(routes, "/%2A/leaf")).toEqual({
+ value: "dynamic",
+ params: { id: "*" },
+ });
+ expect(
+ matchPathnameRoutes(
+ [
+ { pattern: "/a%2Fb%2A/other", value: "encoded literal" },
+ { pattern: "/:id/leaf", value: "dynamic" },
+ ],
+ "/a%2Fb%2A/leaf"
+ )?.params
+ ).toEqual({ id: "a/b*" });
+ });
+
+ test("an encoded NUL cannot impersonate a literal rule placeholder", () => {
+ expect(matchPathnamePattern("/%2A", "/%000%00")).toBeUndefined();
+ });
+
+ test("preserves a previously saved encoded auth rule", () => {
+ const content = JSON.stringify({
+ version: 1,
+ routes: {
+ "/%2A": {
+ method: "basic",
+ login: "admin",
+ password: "secret",
+ },
+ },
+ });
+ const routes = parseWsAuthOrThrow(content, "Saved auth");
+ expect(findWsAuthRoute(routes, "/%2A")?.route).toBe("/%2A");
+ expect(findWsAuthRoute(routes, "/docs")).toBeUndefined();
+ expect(() =>
+ authenticateRequest(new Request("https://example.com/%2A"), routes)
+ ).toThrowError(Response);
+ expect(
+ authenticateRequest(new Request("https://example.com/docs"), routes)
+ ).toBeUndefined();
+ });
+
+ test("returns Remix route parameters", () => {
+ expect(matchPathnamePattern("/docs/:rest*", "/docs/a/b")).toEqual({
+ "*": "a/b",
+ });
+ expect(matchPathnamePattern("/docs/*", "/docs")).toEqual({ "*": "" });
+ expect(matchPathnamePattern("/users/:id", "/users/caf%C3%A9")).toEqual({
+ id: "café",
+ });
+ expect(matchPathnamePattern("/docs/:rest*", "/docs")).toEqual({
+ "*": "",
+ });
+ expect(matchPathnamePattern("/docs/:id?", "/docs")).toEqual({});
+ expect(matchPathnamePattern("/docs/:id?", "/docs/guide")).toEqual({
+ id: "guide",
+ });
+ expect(matchPathnamePattern("/files/:name", "/files/a%2Fb")).toEqual({
+ name: "a/b",
+ });
+ });
+
+ test("selects the route preferred by the published router", () => {
+ const routes = [
+ { pattern: "/a/:x/:y", value: "first" },
+ { pattern: "/:x/b/c", value: "second" },
+ ];
+ expect(matchPathnameRoutes(routes, "/a/b/c")?.value).toBe("second");
+ expect(
+ matchPathnameRoutes(
+ [
+ { pattern: "/docs/*", value: "splat" },
+ { pattern: "/docs", value: "static" },
+ ],
+ "/docs"
+ )?.value
+ ).toBe("static");
+ });
+
+ test("ranks static and splat pages like the published router", () => {
+ const routes = [
+ { pattern: "/docs/*", value: "splat" },
+ { pattern: "/docs/:slug?", value: "optional" },
+ { pattern: "/docs/:slug", value: "dynamic" },
+ { pattern: "/docs/guide", value: "static" },
+ ];
+ expect(matchPathnameRoutes(routes, "/docs/guide")?.value).toBe("static");
+ // Optional and required parameters have equal rank; source order wins.
+ expect(matchPathnameRoutes(routes, "/docs/other")?.value).toBe("optional");
+ expect(matchPathnameRoutes(routes, "/docs/a/b")?.value).toBe("splat");
+ expect(matchPathnameRoutes(routes, "/elsewhere")).toBeUndefined();
+ expect(matchPathnameRoutes([], "/docs")).toBeUndefined();
+ });
+
+ test("keeps the first route when router scores are equal", () => {
+ expect(
+ matchPathnameRoutes(
+ [
+ { pattern: "/:first", value: "first" },
+ { pattern: "/:second", value: "second" },
+ ],
+ "/page"
+ )
+ ).toEqual({ value: "first", params: { first: "page" } });
+ });
+
+ test("authentication still uses the first matching rule", () => {
+ const routes = [
+ createBasicAuthRoute({
+ route: "/*",
+ login: "general",
+ password: "password",
+ }),
+ createBasicAuthRoute({
+ route: "/docs",
+ login: "docs",
+ password: "password",
+ }),
+ ];
+ expect(findWsAuthRoute(routes, "/docs")?.auth.login).toBe("general");
+ expect(findWsAuthRoute(routes, "/docs/guide")?.auth.login).toBe("general");
+ expect(findWsAuthRoute(routes, "/other")?.auth.login).toBe("general");
+ });
+
+ test("authentication scopes a wildcard to its base and descendants", () => {
+ const routes = [
+ createBasicAuthRoute({
+ route: "/private/*",
+ login: "admin",
+ password: "password",
+ }),
+ ];
+ for (const pathname of ["/private", "/private/", "/private/a/b"]) {
+ expect(findWsAuthRoute(routes, pathname)).toBe(routes[0]);
+ }
+ for (const pathname of ["/", "/private-public", "/public/private"]) {
+ expect(findWsAuthRoute(routes, pathname)).toBeUndefined();
+ }
+ });
+
+ test("protects an encoded URL that resolves to an authenticated page", () => {
+ const route = createBasicAuthRoute({
+ route: "/docs",
+ login: "admin",
+ password: "password",
+ });
+ expect(() =>
+ authenticateRequest(new Request("https://example.com/%64ocs"), [route])
+ ).toThrowError(Response);
});
test("builds content from JSON and route sources", () => {
@@ -368,4 +594,56 @@ describe("wsauth", () => {
);
}
});
+
+ test("project domain exemption uses the request URL, not forwarded host headers", () => {
+ const authRoutes = [
+ createBasicAuthRoute({
+ route: "/private/*",
+ login: "admin",
+ password: "secret",
+ }),
+ ];
+ const projectDomain = "project";
+
+ expect(
+ authenticateProjectRequest(
+ new Request("https://project.wstd.work/private"),
+ authRoutes,
+ projectDomain
+ )
+ ).toBeUndefined();
+
+ expect(() =>
+ authenticateProjectRequest(
+ new Request("https://customer.example/private", {
+ headers: { "x-forwarded-host": "project.wstd.work" },
+ }),
+ authRoutes,
+ projectDomain
+ )
+ ).toThrow(Response);
+
+ expect(
+ authenticateProjectRequest(
+ new Request("https://customer.example/private", {
+ headers: {
+ "x-forwarded-host": "project.wstd.work",
+ Authorization: `Basic ${btoa("admin:secret")}`,
+ },
+ }),
+ authRoutes,
+ projectDomain
+ )
+ ).toBe(authRoutes[0]);
+
+ expect(() =>
+ authenticateProjectRequest(
+ new Request("https://customer.example/private", {
+ headers: { Host: "project.wstd.work" },
+ }),
+ authRoutes,
+ projectDomain
+ )
+ ).toThrow(Response);
+ });
});
diff --git a/packages/wsauth/src/index.ts b/packages/wsauth/src/index.ts
index fc79fe4253..4768af602a 100644
--- a/packages/wsauth/src/index.ts
+++ b/packages/wsauth/src/index.ts
@@ -1,4 +1,5 @@
import type { BasicAuthInput, WsAuthConfig } from "./schema";
+import { matchRoutes } from "@remix-run/router";
export type { BasicAuthInput, WsAuthConfig } from "./schema";
export type BasicAuthRule = {
@@ -197,6 +198,23 @@ const isRecord = (value: unknown): value is Record<string, unknown> => {
const parameterSegment = /^:\w+[?*]?$/;
+const decodeStaticSegment = (segment: string) => {
+ if (segment.includes("%") === false) {
+ return { path: segment };
+ }
+ try {
+ const decoded = decodeURIComponent(segment);
+ return {
+ // Remix decodes request paths; keep encoded slashes within one segment.
+ path: decoded.replaceAll("/", "%2F"),
+ // These were valid literal segments before route matching used Remix.
+ literal: decoded.startsWith(":") || /[?*%]/.test(decoded),
+ };
+ } catch {
+ return { path: segment, literal: true };
+ }
+};
+
/** Validate the route-rule syntax shared by authentication and response headers. */
export const validatePathnamePattern = (route: string) => {
if (route.startsWith("/") === false) {
@@ -205,7 +223,7 @@ export const validatePathnamePattern = (route: string) => {
if (route === "/") {
return;
}
- if (route !== "/" && route.endsWith("/")) {
+ if (route.endsWith("/")) {
return 'Route must not end with "/"';
}
if (route.includes("//")) {
@@ -226,6 +244,9 @@ export const validatePathnamePattern = (route: string) => {
if (segment.startsWith(":") && parameterSegment.test(segment) === false) {
return `Invalid route parameter "${segment}"`;
}
+ if (segment.includes("?") && parameterSegment.test(segment) === false) {
+ return 'Optional marker "?" is only allowed on a named parameter';
+ }
if (segment.includes("*")) {
return "Wildcard can only be used as * or :name*";
}
@@ -428,57 +449,102 @@ export const getBasicAuthCredentials = (authorization: string | null) => {
return auth?.credentials;
};
-const normalizePathname = (pathname: string) => {
- if (pathname === "" || pathname === "/") {
- return "/";
- }
- return pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
-};
-
-/**
- * Boolean matcher for auth and response-header rules. A trailing wildcard also
- * matches its base path (`/docs/*` matches `/docs`). Page routing instead uses
- * project-build's `matchUrlPattern`, which returns decoded path parameters and
- * does not match `/docs` for that pattern.
- */
-export const matchesPathnamePattern = (route: string, pathname: string) => {
- const routeSegments = normalizePathname(route).slice(1).split("/");
- const pathnameSegments = normalizePathname(pathname).slice(1).split("/");
- const matchSegments = (
- routeIndex: number,
- pathnameIndex: number
- ): boolean => {
- const routeSegment = routeSegments[routeIndex];
- const pathnameSegment = pathnameSegments[pathnameIndex];
- if (routeSegment === undefined) {
- return pathnameSegment === undefined;
- }
- if (routeSegment === "*" || /^:\w+\*$/.test(routeSegment)) {
- return routeIndex === routeSegments.length - 1;
- }
- if (/^:\w+\?$/.test(routeSegment)) {
- return (
- matchSegments(routeIndex + 1, pathnameIndex) ||
- (pathnameSegment !== undefined &&
- matchSegments(routeIndex + 1, pathnameIndex + 1))
- );
+// Remix performs route matching; literal encoded segments need placeholders so
+// saved rules such as /%2A cannot turn into router syntax.
+const toRouterPattern = (
+ pattern: string,
+ literals: Map<string, string>,
+ decodedPathname: string
+) => {
+ const segments: string[] = [];
+ for (const segment of (pattern || "/").replace(/:\w+\*$/, "*").split("/")) {
+ if (segment === "*" || segment.startsWith(":")) {
+ segments.push(segment);
+ continue;
}
- if (pathnameSegment === undefined) {
- return false;
+ const decoded = decodeStaticSegment(segment);
+ if (decoded.literal) {
+ let marker = literals.get(segment);
+ if (marker === undefined) {
+ let index = literals.size;
+ marker = `\0${index}\0`;
+ while (
+ decodedPathname.includes(marker) ||
+ Array.from(literals.values()).includes(marker)
+ ) {
+ index += 1;
+ marker = `\0${index}\0`;
+ }
+ literals.set(segment, marker);
+ }
+ segments.push(marker);
+ continue;
}
- if (/^:\w+$/.test(routeSegment)) {
- return matchSegments(routeIndex + 1, pathnameIndex + 1);
+ segments.push(decoded.path);
+ }
+ return segments.join("/");
+};
+
+/** Match a set of page paths with the same route ranking as the published app. */
+export const matchPathnameRoutes = <Value>(
+ routes: ReadonlyArray<{ pattern: string; value: Value }>,
+ pathname: string
+): { value: Value; params: Record<string, string | undefined> } | undefined => {
+ const literals = new Map<string, string>();
+ const decodedPathname = pathname
+ .split("/")
+ .map((segment) => {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+ })
+ .join("/");
+ const routerRoutes = routes.map((route) => ({
+ path: toRouterPattern(route.pattern, literals, decodedPathname),
+ caseSensitive: false,
+ source: route,
+ }));
+ const decodedLiterals = Array.from(literals, ([literal, marker]) => {
+ try {
+ return [marker, decodeURIComponent(literal)] as const;
+ } catch {
+ return [marker, literal] as const;
}
- return (
- routeSegment === pathnameSegment &&
- matchSegments(routeIndex + 1, pathnameIndex + 1)
- );
+ });
+ const routerPathname = pathname
+ .split("/")
+ .map((segment) => literals.get(segment) ?? segment)
+ .join("/");
+ const match = matchRoutes(routerRoutes, routerPathname)?.at(-1);
+ if (match === undefined) {
+ return;
+ }
+ return {
+ value: match.route.source.value,
+ params: Object.fromEntries(
+ Object.entries(match.params).map(([name, value]) => [
+ name,
+ value === undefined
+ ? value
+ : decodedLiterals.reduce(
+ (result, [marker, literal]) => result.replaceAll(marker, literal),
+ value
+ ),
+ ])
+ ),
};
- return matchSegments(0, 0);
};
+/** Match one project rule or page path using the published app's route semantics. */
+export const matchPathnamePattern = (pattern: string, pathname: string) =>
+ matchPathnameRoutes([{ pattern, value: true }], pathname)?.params;
+
export const findWsAuthRoute = (authRoutes: WsAuthRoute[], pathname: string) =>
- authRoutes.find(({ route }) => matchesPathnamePattern(route, pathname));
+ authRoutes.find(
+ ({ route }) => matchPathnamePattern(route, pathname) !== undefined
+ );
export const authenticateRequest = (
request: Request,
@@ -504,3 +570,19 @@ export const authenticateRequest = (
});
}
};
+
+/** Skip project authentication only on the actual project hostname. */
+export const authenticateProjectRequest = (
+ request: Request,
+ authRoutes: WsAuthRoute[],
+ projectDomain?: string
+) => {
+ const hostname = new URL(request.url).hostname;
+ if (
+ projectDomain !== undefined &&
+ (hostname === projectDomain || hostname.startsWith(`${projectDomain}.`))
+ ) {
+ return;
+ }
+ return authenticateRequest(request, authRoutes);
+};
diff --git a/packages/wsauth/src/package.test.ts b/packages/wsauth/src/package.test.ts
index 1037970afe..f47dcc2337 100644
--- a/packages/wsauth/src/package.test.ts
+++ b/packages/wsauth/src/package.test.ts
@@ -1,18 +1,12 @@
import { execFile } from "node:child_process";
-import { createRequire } from "node:module";
-import { cp, mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { delimiter, dirname, join } from "node:path";
+import { cp, mkdtemp, mkdir, rm } from "node:fs/promises";
+import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
-import { afterEach, test } from "vitest";
+import { afterEach, expect, test } from "vitest";
const execFileAsync = promisify(execFile);
-const require = createRequire(import.meta.url);
const packageDirectory = fileURLToPath(new URL("..", import.meta.url));
-const workspaceDirectory = fileURLToPath(new URL("../../..", import.meta.url));
-const tsc = join(workspaceDirectory, "node_modules/.bin/tsc");
-const packageBinDirectory = join(workspaceDirectory, "node_modules/.bin");
let temporaryDirectory: string | undefined;
afterEach(async () => {
@@ -22,18 +16,13 @@ afterEach(async () => {
}
});
-test("publishes type declarations for every public entrypoint", async () => {
- temporaryDirectory = await mkdtemp(join(tmpdir(), "webstudio-wsauth-pack-"));
- const packDirectory = join(temporaryDirectory, "pack");
+test("packs declarations for every public entrypoint", async () => {
+ // Stage inside the package so its normal workspace dependencies resolve.
+ temporaryDirectory = await mkdtemp(join(packageDirectory, ".package-test-"));
const stagingDirectory = join(temporaryDirectory, "staging");
- const projectDirectory = join(temporaryDirectory, "project");
- await Promise.all([
- mkdir(packDirectory, { recursive: true }),
- mkdir(stagingDirectory, { recursive: true }),
- mkdir(projectDirectory, { recursive: true }),
- ]);
- await Promise.all([
- ...[
+ await mkdir(stagingDirectory);
+ await Promise.all(
+ [
"package.json",
"README.md",
"src",
@@ -43,90 +32,26 @@ test("publishes type declarations for every public entrypoint", async () => {
cp(join(packageDirectory, entry), join(stagingDirectory, entry), {
recursive: true,
})
- ),
- ...[
- ["zod", dirname(require.resolve("zod/package.json"))],
- ["@types/node", dirname(require.resolve("@types/node/package.json"))],
- [
- "@webstudio-is/tsconfig",
- dirname(require.resolve("@webstudio-is/tsconfig/package.json")),
- ],
- ["undici-types", dirname(require.resolve("undici-types/package.json"))],
- ].map(async ([name, source]) => {
- const destination = join(stagingDirectory, "node_modules", name);
- await mkdir(dirname(destination), { recursive: true });
- await cp(source, destination, { recursive: true });
- }),
- ]);
+ )
+ );
+
+ await execFileAsync("pnpm", ["build"], { cwd: stagingDirectory });
+ await execFileAsync("pnpm", ["dts"], { cwd: stagingDirectory });
- const env = {
- ...process.env,
- PATH: `${packageBinDirectory}${delimiter}${process.env.PATH ?? ""}`,
- };
- await execFileAsync("pnpm", ["build"], { cwd: stagingDirectory, env });
- await execFileAsync("pnpm", ["dts"], { cwd: stagingDirectory, env });
const packed = JSON.parse(
(
- await execFileAsync(
- "npm",
- ["pack", "--json", "--pack-destination", packDirectory],
- { cwd: stagingDirectory }
- )
+ await execFileAsync("npm", ["pack", "--dry-run", "--json"], {
+ cwd: stagingDirectory,
+ })
).stdout
- ) as Array<{ filename: string }>;
- const archive = join(packDirectory, packed[0]?.filename ?? "");
- await writeFile(
- join(projectDirectory, "package.json"),
- JSON.stringify({
- private: true,
- type: "module",
- dependencies: {
- "@webstudio-is/wsauth": `file:${archive}`,
- zod: `file:${dirname(require.resolve("zod/package.json"))}`,
- },
- }),
- "utf8"
- );
- await execFileAsync(
- "npm",
- [
- "install",
- "--ignore-scripts",
- "--no-package-lock",
- "--no-audit",
- "--no-fund",
- ],
- { cwd: projectDirectory }
- );
- await writeFile(
- join(projectDirectory, "index.ts"),
- `import { matchesPathnamePattern, validatePathnamePattern } from "@webstudio-is/wsauth";
-import type { WsAuthResources } from "@webstudio-is/wsauth";
-import type { WsAuthConfig } from "@webstudio-is/wsauth/schema";
-
-const routes: WsAuthResources["routes"] = [];
-const config: WsAuthConfig = { version: 1, routes: {} };
-const matches: boolean = matchesPathnamePattern("/*", "/docs");
-const routeError: string | undefined = validatePathnamePattern("/docs/*");
-void [routes, config, matches, routeError];
-`,
- "utf8"
- );
-
- await execFileAsync(
- tsc,
- [
- "--ignoreConfig",
- "--noEmit",
- "--strict",
- "--moduleResolution",
- "bundler",
- "--module",
- "esnext",
- "--target",
- "es2022",
- "index.ts",
- ],
- { cwd: projectDirectory }
+ ) as Array<{ files: Array<{ path: string }> }>;
+ const packedFiles = packed[0]?.files.map((file) => file.path);
+ expect(packedFiles).toEqual(
+ expect.arrayContaining([
+ "lib/index.js",
+ "lib/schema.js",
+ "lib/types/index.d.ts",
+ "lib/types/schema.d.ts",
+ ])
);
}, 30_000);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 512e13df7c..e266683863 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3177,6 +3177,9 @@ importers:
packages/wsauth:
dependencies:
+ '@remix-run/router':
+ specifier: 1.23.0
+ version: 1.23.0
zod:
specifier: ^4.4.3
version: 4.4.3