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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Basic authentication (#5779)
Oleg Isonen16fa5ab0e37b
diff --git a/apps/builder/.env b/apps/builder/.envindex 1a9cafa86d..c5eb8e04c1 100644--- a/apps/builder/.env+++ b/apps/builder/.env@@ -60,6 +60,7 @@ PLANS='["canRestoreBackups": true,"allowAdditionalPermissions": true,"allowDynamicData": true,+ "allowAuth": true,"allowContentMode": true,"allowStagingPublish": true,"maxContactEmailsPerProject": 5,diff --git a/apps/builder/app/builder/features/pages/page-settings.stories.tsx b/apps/builder/app/builder/features/pages/page-settings.stories.tsxindex 149d602fa1..e6c67349ef 100644--- a/apps/builder/app/builder/features/pages/page-settings.stories.tsx+++ b/apps/builder/app/builder/features/pages/page-settings.stories.tsx@@ -1,5 +1,5 @@import { $pages } from "~/shared/sync/data-stores";-import { PageSettings as PageSettingsComponent } from "./page-settings";+import { PageSettings as PageSettingsComponent } from "./page-settings/page-settings";import {Grid,theme,diff --git a/apps/builder/app/builder/features/pages/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings.tsxdeleted file mode 100644index b7b4cfcea7..0000000000--- a/apps/builder/app/builder/features/pages/page-settings.tsx+++ /dev/null@@ -1,1647 +0,0 @@-import { nanoid } from "nanoid";-import { z } from "zod";-import {- type FocusEventHandler,- useState,- useCallback,- useId,- useEffect,- type JSX,- useRef,-} from "react";-import { useStore } from "@nanostores/react";-import { useDebouncedCallback } from "use-debounce";-import * as bcp47 from "bcp-47";-import slugify from "slugify";-import {- type Page,- type Pages,- PageName,- HomePagePath,- PageTitle,- PagePath,- getPagePath,- findPageByIdOrPath,- ROOT_FOLDER_ID,- findParentFolderByChildId,- ProjectNewRedirectPath,- isLiteralExpression,- documentTypes,- getHomePage,- elementComponent,-} from "@webstudio-is/sdk";-import {- theme,- Button,- Box,- Label,- TextArea,- InputErrorsTooltip,- Tooltip,- InputField,- Grid,- Checkbox,- Separator,- Text,- ScrollArea,- rawTheme,- Flex,- Select,- Link,- buttonStyle,- PanelBanner,- css,- Switch,- TitleSuffixSpacer,- ProBadge,- DialogClose,- DialogTitle,- DialogTitleActions,-} from "@webstudio-is/design-system";-import {- CopyIcon,- TrashIcon,- HomeIcon,- InfoCircleIcon,- UploadIcon,-} from "@webstudio-is/icons";-import { useIds } from "~/shared/form-utils";-import {- $publishedOrigin,- $permissions,- $isDesignMode,-} from "~/shared/nano-states";-import { $assets } from "~/shared/sync/data-stores";-import { $project } from "~/shared/sync/data-stores";-import { $openProjectSettings } from "~/shared/nano-states/project-settings";-import { $instances, $pages } from "~/shared/sync/data-stores";-import {- BindingControl,- BindingPopover,-} from "~/builder/shared/binding-popover";-import { serverSyncStore } from "~/shared/sync/sync-stores";-// @todo should be moved to shared because features should not depend on features-import { ImageControl } from "~/shared/project-settings";-// @todo should be moved to shared because features should not depend on features-import { useEffectEvent } from "~/shared/hook-utils/effect-event";-import {- compilePathnamePattern,- tokenizePathnamePattern,- validatePathnamePattern,-} from "~/builder/shared/url-pattern";-import { useUnmount } from "~/shared/hook-utils/use-mount";-import { selectInstance } from "~/shared/nano-states";-import { computeExpression } from "~/shared/data-variables";-import { $currentSystem } from "~/shared/system";-import { Card } from "../marketplace/card";-import { ImageInfo } from "./image-info";-import { SearchPreview } from "./search-preview";-import { SocialPreview } from "./social-preview";-import {- registerFolderChildMutable,- cleanupChildRefsMutable,- $pageRootScope,- duplicatePage,- isPathAvailable,-} from "./page-utils";-import { Form } from "./form";-import { CustomMetadata } from "./custom-metadata";-import { findMatchingRedirect } from "~/shared/project-settings/utils";-import {- LOOP_ERROR,- wouldCreateLoop,-} from "~/shared/redirects/redirect-loop-detection";--const fieldDefaultValues = {- name: "Untitled",- parentFolderId: ROOT_FOLDER_ID,- path: "/untitled",- isHomePage: false,- title: `"Untitled"`,- description: `""`,- excludePageFromSearch: `true`,- language: `""`,- socialImageUrl: `""`,- socialImageAssetId: "",- status: undefined as string | undefined,- redirect: `""`,- documentType: "html" as (typeof documentTypes)[number],- customMetas: [{ property: "", content: `""` }],- marketplaceInclude: false,- marketplaceCategory: "",- marketplaceThumbnailAssetId: "",-};--const fieldNames = Object.keys(- fieldDefaultValues-) as (keyof typeof fieldDefaultValues)[];--type FieldName = (typeof fieldNames)[number];--type Values = typeof fieldDefaultValues;--type OnChange = (- event: {- [K in keyof Values]: {- field: K;- value: Values[K];- };- }[keyof Values]-) => void;--type Errors = {- [fieldName in FieldName]?: string[];-};--const EmptyString = z.string().refine((string) => string === "");--// 2xx, 3xx, 4xx, 5xx-const statusRegex = /^[2345]\d\d$/;-const Status = z- .number()- .refine(- (value) => statusRegex.test(String(value)),- "Status code expects 2xx, 3xx, 4xx or 5xx"- );--const Language = z- .string()- .refine(- (value) => bcp47.parse(value).language !== null,- "The language is invalid"- );--const SharedPageValues = z.object({- name: PageName,- title: PageTitle,- description: z.string().optional(),- excludePageFromSearch: z.boolean().optional(),- language: Language.or(EmptyString),- socialImageUrl: z.string().optional(),- status: Status.optional(),- redirect: z.optional(ProjectNewRedirectPath.or(EmptyString)),- documentType: z.optional(z.enum(documentTypes)),- customMetas: z- .array(- z.object({- property: z.string(),- content: z.string(),- })- )- .optional(),-});--const HomePageValues = SharedPageValues.extend({- path: HomePagePath,-});--const PageValues = SharedPageValues.extend({- path: PagePath,-});--const validateValues = (- pages: undefined | Pages,- // undefined page id means new page- pageId: undefined | Page["id"],- values: Values,- variableValues: Map<string, unknown>-): Errors => {- // Null or undefined in the field value is only possible if it’s a dynamic (expression) value.- // We do not validate dynamic values but instead provide a default value for validation.- const excludeFromValidationDefault = "exclude from validation";-- const computedValues = {- name: values.name,- path: values.path,- title:- computeExpression(values.title, variableValues) ??- excludeFromValidationDefault,- description: computeExpression(values.description, variableValues),- excludePageFromSearch: computeExpression(- values.excludePageFromSearch,- variableValues- ),- language: computeExpression(values.language, variableValues),- socialImageUrl: computeExpression(values.socialImageUrl, variableValues),- status: computeExpression(values.status ?? `undefined`, variableValues),- redirect: computeExpression(values.redirect, variableValues),- customMetas: values.customMetas.map((item) => ({- property: item.property,- content: computeExpression(item.content, variableValues),- })),- };-- const Validator = values.isHomePage ? HomePageValues : PageValues;- const parsedResult = Validator.safeParse(computedValues);- const errors: Errors = {};- if (parsedResult.success === false) {- return parsedResult.error.formErrors.fieldErrors;- }- if (pages !== undefined && values.path !== undefined) {- if (- isPathAvailable({- pages,- path: values.path,- parentFolderId: values.parentFolderId,- pageId,- }) === false- ) {- errors.path = errors.path ?? [];- errors.path.push("All paths must be unique");- }- const messages = validatePathnamePattern(values.path);- if (messages.length > 0) {- errors.path = errors.path ?? [];- errors.path.push(...messages);- }- }-- // Validate redirect doesn't create a loop- if (- pages !== undefined &&- values.path !== undefined &&- computedValues.redirect &&- typeof computedValues.redirect === "string" &&- computedValues.redirect !== ""- ) {- const existingRedirects = pages.redirects ?? [];- if (- wouldCreateLoop(values.path, computedValues.redirect, existingRedirects)- ) {- errors.redirect = errors.redirect ?? [];- errors.redirect.push(LOOP_ERROR);- }- }-- return errors;-};--const toFormValues = (- page: Page,- pages: Pages,- isHomePage: boolean-): Values => {- const parentFolder = findParentFolderByChildId(page.id, pages.folders);- return {- name: page.name,- parentFolderId: parentFolder?.id ?? pages.rootFolderId,- path: page.path,- title: page.title,- description: page.meta.description ?? fieldDefaultValues.description,- socialImageUrl:- page.meta.socialImageUrl ?? fieldDefaultValues.socialImageUrl,- socialImageAssetId:- page.meta.socialImageAssetId ?? fieldDefaultValues.socialImageAssetId,- excludePageFromSearch:- page.meta.excludePageFromSearch ??- fieldDefaultValues.excludePageFromSearch,- language: page.meta.language ?? fieldDefaultValues.language,- status: page.meta.status ?? fieldDefaultValues.status,- redirect: page.meta.redirect ?? fieldDefaultValues.redirect,- documentType: page.meta.documentType ?? fieldDefaultValues.documentType,- isHomePage,- customMetas: page.meta.custom ?? fieldDefaultValues.customMetas,- marketplaceInclude: page.marketplace?.include ?? false,- marketplaceCategory: page.marketplace?.category ?? "",- marketplaceThumbnailAssetId: page.marketplace?.thumbnailAssetId ?? "",- };-};--const autoSelectHandler: FocusEventHandler<HTMLInputElement> = (event) =>- event.target.select();--const PathField = ({- errors,- value,- onChange,-}: {- errors?: string[];- value: string;- onChange: (value: string) => void;-}) => {- const { allowDynamicData } = useStore($permissions);- const id = useId();- return (- <Grid gap={1}>- <Flex align="center" gap={1}>- <Label htmlFor={id}>Path</Label>- {allowDynamicData === false && <ProBadge>PRO</ProBadge>}- <Tooltip- content={- <>- <Text>- 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 whole remaining part at the end of the URL.- </Text>- {allowDynamicData === false && (- <>- <br />- <Text>- To make the path dynamic and use it with CMS, you can use- parameters and other features. You can publish to staging- for free; upgrade to Pro to publish to custom domains.- </Text>- <Link- className={buttonStyle({ color: "gradient" })}- css={{ marginTop: theme.spacing[5], width: "100%" }}- color="contrast"- underline="none"- target="_blank"- href="https://webstudio.is/pricing"- >- Upgrade- </Link>- </>- )}- </>- }- variant="wrapped"- >- <InfoCircleIcon- color={rawTheme.colors.foregroundSubtle}- tabIndex={-1}- />- </Tooltip>- </Flex>- <InputErrorsTooltip errors={errors}>- <InputField- color={errors && "error"}- id={id}- placeholder="/about"- value={value}- onChange={(event) => onChange(event.target.value)}- />- </InputErrorsTooltip>- </Grid>- );-};--const StatusField = ({- errors,- value = `undefined`,- onChange,-}: {- errors?: string[];- value: undefined | string;- onChange: (value: undefined | string) => void;-}) => {- const id = useId();- const { variableValues, scope, aliases } = useStore($pageRootScope);- return (- <Grid gap={1}>- <Flex align="center" gap={1}>- <Label htmlFor={id}>Status code </Label>- <Tooltip- content={- <Text>- Status code value can be a{" "}- <Link- color="inherit"- target="_blank"- href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status"- >- HTTP Status- </Link>{" "}- number or an expression that returns the status code dynamic- response handling.- </Text>- }- variant="wrapped"- >- <InfoCircleIcon- color={rawTheme.colors.foregroundSubtle}- tabIndex={-1}- />- </Tooltip>- </Flex>- <BindingControl>- <BindingPopover- scope={scope}- aliases={aliases}- variant={isLiteralExpression(value) ? "default" : "bound"}- value={value}- onChange={onChange}- onRemove={(evaluatedValue) =>- onChange(JSON.stringify(evaluatedValue ?? ""))- }- />- <InputErrorsTooltip errors={errors}>- <InputField- inputMode="numeric"- color={errors && "error"}- id={id}- placeholder="200"- disabled={isLiteralExpression(value) === false}- value={String(computeExpression(value, variableValues) ?? "")}- onChange={(event) => {- if (event.target.value === "") {- onChange(undefined);- } else {- const number = Number(event.target.value);- const status =- Number.isNaN(number) || String(number) !== event.target.value- ? event.target.value- : number;- onChange(JSON.stringify(status));- }- }}- />- </InputErrorsTooltip>- </BindingControl>- </Grid>- );-};--const RedirectField = ({- errors,- value,- onChange,-}: {- errors?: string[];- value: string;- onChange: (value: string) => void;-}) => {- const id = useId();- const { allowDynamicData } = useStore($permissions);- const { variableValues, scope, aliases } = useStore($pageRootScope);- return (- <Grid gap={1}>- <Flex align="center" gap={1}>- <Label htmlFor={id}>Redirect </Label>- {allowDynamicData === false && <ProBadge>PRO</ProBadge>}- <Tooltip- content="Redirect value can be a path or an expression that returns a path for dynamic response handling."- variant="wrapped"- >- <InfoCircleIcon- color={rawTheme.colors.foregroundSubtle}- tabIndex={-1}- />- </Tooltip>- </Flex>-- <BindingControl>- <BindingPopover- scope={scope}- aliases={aliases}- variant={isLiteralExpression(value) ? "default" : "bound"}- value={value}- onChange={onChange}- onRemove={(evaluatedValue) =>- onChange(JSON.stringify(evaluatedValue ?? ""))- }- />- <InputErrorsTooltip errors={errors}>- <InputField- color={errors && "error"}- id={id}- placeholder="/another-path"- disabled={isLiteralExpression(value) === false}- value={String(computeExpression(value, variableValues))}- onChange={(event) => onChange(JSON.stringify(event.target.value))}- />- </InputErrorsTooltip>- </BindingControl>- </Grid>- );-};--const LanguageField = ({- errors,- value,- onChange,-}: {- errors?: string[];- value: string;- onChange: (value: string) => void;-}) => {- const id = useId();- const { variableValues, scope, aliases } = useStore($pageRootScope);- return (- <Grid gap={1}>- <Label htmlFor={id}>Language</Label>- <BindingControl>- <BindingPopover- scope={scope}- aliases={aliases}- variant={isLiteralExpression(value) ? "default" : "bound"}- value={value}- onChange={onChange}- onRemove={(evaluatedValue) =>- onChange(JSON.stringify(evaluatedValue ?? ""))- }- />- <InputErrorsTooltip errors={errors}>- <InputField- color={errors && "error"}- id={id}- placeholder="en-US"- disabled={isLiteralExpression(value) === false}- value={String(computeExpression(value, variableValues))}- onChange={(event) => onChange(JSON.stringify(event.target.value))}- />- </InputErrorsTooltip>- </BindingControl>- </Grid>- );-};--/**- * Compute the full page path from form values.- * This combines folder path with page path, handling home page special case.- */-const computePagePath = (values: Values, pages: Pages): string => {- if (values.isHomePage) {- return "/";- }- const foldersPath = getPagePath(values.parentFolderId, pages);- return [foldersPath, values.path]- .filter(Boolean)- .join("/")- .replace(/\/+/g, "/");-};--const usePageUrl = (values: Values) => {- const pages = useStore($pages);- const path = pages === undefined ? "" : computePagePath(values, pages);-- const system = useStore($currentSystem);- const publishedOrigin = useStore($publishedOrigin);- const tokens = tokenizePathnamePattern(path);- const compiledPath = compilePathnamePattern(tokens, system.params);- return `${publishedOrigin}${compiledPath}`;-};--const fieldsetStyle = css({- all: "unset",- display: "block",- "&:disabled": {- opacity: 0.4,- },-});--const MarketplaceSection = ({- values,- onChange,-}: {- values: Values;- onChange: OnChange;-}) => {- const excludeId = useId();- const categoryId = useId();- const categoryMeta = values.customMetas.find(- ({ property }) => property === "ws:category"- );- // @todo remove after all stores are migrated- const categoryFallback = String(- computeExpression(categoryMeta?.content ?? `""`, new Map())- );- const category = values.marketplaceCategory ?? categoryFallback ?? "Pages";- const assets = useStore($assets);- const thumbnailAsset = assets.get(values.marketplaceThumbnailAssetId);- const thumnailFallbackAsset = assets.get(values.socialImageAssetId);- return (- <Grid gap={2} css={{ padding: theme.panel.padding }}>- <Label text="title">Marketplace</Label>- <Grid- flow="column"- gap={1}- justify="start"- align="center"- css={{ py: theme.spacing[2] }}- >- <Switch- id={excludeId}- checked={values.marketplaceInclude}- onCheckedChange={(value) =>- onChange({ field: "marketplaceInclude", value })- }- />- <Label htmlFor={excludeId}>Include in the marketplace</Label>- </Grid>- <Grid gap={1}>- <Label htmlFor={categoryId}>Category</Label>- <InputField- id={categoryId}- name="marketplaceCategory"- value={values.marketplaceCategory}- onChange={(event) =>- onChange({- field: "marketplaceCategory",- value: event.target.value,- })- }- />- </Grid>- <Grid gap={1} flow="column">- <ImageControl- onAssetIdChange={(value) =>- onChange({ field: "marketplaceThumbnailAssetId", value })- }- >- <Button color="neutral" css={{ justifySelf: "start" }}>- Choose thumbnail from assets- </Button>- </ImageControl>- </Grid>- {thumbnailAsset?.type === "image" && (- <ImageInfo- asset={thumbnailAsset}- onDelete={() =>- onChange({ field: "marketplaceThumbnailAssetId", value: "" })- }- />- )}- <Grid gap={1}>- <Label>Marketplace preview</Label>- <Box- css={{- padding: theme.spacing[5],- borderRadius: theme.borderRadius[4],- border: `1px solid ${theme.colors.borderMain}`,- justifySelf: "start",- }}- >- <Grid gap={1} css={{ width: theme.spacing[30] }}>- {category && <Label text="title">{category}</Label>}- <Card- title={values.name}- image={thumbnailAsset ?? thumnailFallbackAsset}- />- </Grid>- </Box>- </Grid>- </Grid>- );-};--const FormFields = ({- autoSelect,- errors,- values,- onChange,-}: {- autoSelect?: boolean;- errors: Errors;- values: Values;- onChange: OnChange;-}) => {- const project = useStore($project);- const fieldIds = useIds(fieldNames);- const assets = useStore($assets);- const pages = useStore($pages);- const { allowDynamicData } = useStore($permissions);- const { variableValues, scope, aliases } = useStore($pageRootScope);-- const pageUrl = usePageUrl(values);-- if (pages === undefined) {- return;- }-- const socialImageAsset = assets.get(values.socialImageAssetId);- const faviconAsset = assets.get(pages.meta?.faviconAssetId ?? "");-- const faviconUrl = faviconAsset?.type === "image" ? faviconAsset.name : "";-- const title = String(computeExpression(values.title, variableValues));- const description = String(- computeExpression(values.description, variableValues)- );- const socialImageUrl = String(- computeExpression(values.socialImageUrl, variableValues)- );- const excludePageFromSearch = Boolean(- computeExpression(values.excludePageFromSearch, variableValues)- );-- // Check if any redirect matches this page's path- const fullPagePath = computePagePath(values, pages);- const matchingRedirect = findMatchingRedirect(- fullPagePath,- pages.redirects ?? []- );-- return (- <Grid css={{ height: "100%" }}>- <ScrollArea>- {matchingRedirect && (- <PanelBanner variant="warning">- <Text>- A redirect from "{matchingRedirect.old}" will override this page.- The page will not be rendered when published.{" "}- <Link- color="inherit"- underline="always"- onClick={() => {- $openProjectSettings.set("redirects");- }}- >- Go to Redirects settings- </Link>- </Text>- </PanelBanner>- )}- {/**- * ----------------------========<<<Page props>>>>========----------------------- */}- <Grid gap={2} css={{ padding: theme.panel.padding }}>- <Grid gap={1}>- <Label htmlFor={fieldIds.name}>Page name</Label>- <InputErrorsTooltip errors={errors.name}>- <InputField- color={errors.name && "error"}- id={fieldIds.name}- autoFocus- onFocus={autoSelect ? autoSelectHandler : undefined}- name="name"- placeholder="About"- value={values.name}- onChange={(event) => {- onChange({ field: "name", value: event.target.value });- }}- />- </InputErrorsTooltip>-- <Grid flow={"column"} gap={1} justify={"start"} align={"center"}>- {values.isHomePage ? (- <>- <HomeIcon />- <Text- css={{- overflowWrap: "anywhere",- wordBreak: "break-all",- my: 2,- }}- >- “{values.name}” is the home page- </Text>- </>- ) : values.parentFolderId !== pages.rootFolderId ? (- <>- <HomeIcon color={rawTheme.colors.foregroundSubtle} />- <Text- css={{- overflowWrap: "anywhere",- wordBreak: "break-all",- my: 2,- }}- color="subtle"- >- Move this page to the “Root” folder to set it as your home- page- </Text>- </>- ) : values.documentType === "xml" ? (- <>- <HomeIcon color={rawTheme.colors.foregroundSubtle} />- <Text- css={{- overflowWrap: "anywhere",- wordBreak: "break-all",- my: 2,- }}- color="subtle"- >- XML pages cannot be set as the home page- </Text>- </>- ) : (- <>- <Checkbox- id={fieldIds.isHomePage}- onCheckedChange={() => {- onChange({ field: "path", value: "" });- onChange({- field: "isHomePage",- value: !values.isHomePage,- });- }}- />- <Label- css={{- overflowWrap: "anywhere",- wordBreak: "break-all",- }}- htmlFor={fieldIds.isHomePage}- >- Make “{values.name}” the home page- </Label>- </>- )}- </Grid>- </Grid>-- {values.isHomePage === false && (- <PathField- errors={errors.path}- value={values.path}- onChange={(value) => onChange({ field: "path", value })}- />- )}-- <StatusField- errors={errors.status}- value={values.status}- onChange={(value) => onChange({ field: "status", value })}- />- <RedirectField- errors={errors.redirect}- value={values.redirect}- onChange={(value) => onChange({ field: "redirect", value })}- />- {allowDynamicData === false && (- <PanelBanner>- <Text>- Dynamic routing and redirect are part of the CMS functionality.- You can publish to staging for free; upgrade to Pro to publish- to custom domains.- </Text>- <Flex align="center" gap={1}>- <UploadIcon />- <Link- color="inherit"- target="_blank"- href="https://webstudio.is/pricing"- >- Upgrade to Pro- </Link>- </Flex>- </PanelBanner>- )}-- <Grid gap={1}>- <Label htmlFor={fieldIds.documentType}>Document type</Label>- <Select- options={documentTypes}- getValue={(docType: (typeof documentTypes)[number]) => docType}- getLabel={(docType: (typeof documentTypes)[number]) =>- docType.toLocaleUpperCase()- }- value={values.documentType}- disabled={values.isHomePage}- onChange={(value) => {- onChange({- field: "documentType",- value,- });- }}- />- </Grid>- </Grid>-- <Separator />-- {/**- * ----------------------========<<<Search Results>>>>========----------------------- */}- <fieldset- disabled={values.documentType === "xml"}- className={fieldsetStyle()}- >- <Grid gap={2} css={{ my: theme.spacing[5], mx: theme.spacing[8] }}>- <Grid gap={2}>- <Label text="title">Search</Label>- <Text color="subtle">- Optimize the way this page appears in search engine results- pages.- </Text>- <Grid gap={1}>- <Label>Search result preview</Label>- <Box- css={{- padding: theme.spacing[5],- background: theme.colors.white,- borderRadius: theme.borderRadius[4],- border: `1px solid ${theme.colors.borderMain}`,- }}- >- <Box- css={{- transformOrigin: "top left",- transform: "scale(0.667)",- width: 600,- height: 80,- }}- >- <SearchPreview- siteName={pages?.meta?.siteName ?? ""}- faviconUrl={faviconUrl}- pageUrl={pageUrl}- titleLink={title}- snippet={description}- />- </Box>- </Box>- </Grid>- </Grid>-- <Grid gap={1}>- <Label htmlFor={fieldIds.title}>Title</Label>- <BindingControl>- <BindingPopover- scope={scope}- aliases={aliases}- variant={- isLiteralExpression(values.title) ? "default" : "bound"- }- value={values.title}- onChange={(value) => {- onChange({- field: "title",- value,- });- }}- onRemove={(evaluatedValue) => {- onChange({- field: "title",- value: JSON.stringify(evaluatedValue ?? ""),- });- }}- />- <InputErrorsTooltip errors={errors.title}>- <InputField- color={errors.title && "error"}- id={fieldIds.title}- name="title"- placeholder="My awesome project - About"- disabled={isLiteralExpression(values.title) === false}- value={title}- onChange={(event) => {- onChange({- field: "title",- value: JSON.stringify(event.target.value),- });- }}- />- </InputErrorsTooltip>- </BindingControl>- </Grid>-- <Grid gap={1}>- <Label htmlFor={fieldIds.description}>Description</Label>- <BindingControl>- <BindingPopover- scope={scope}- aliases={aliases}- variant={- isLiteralExpression(values.description)- ? "default"- : "bound"- }- value={values.description}- onChange={(value) => {- onChange({- field: "description",- value,- });- }}- onRemove={(evaluatedValue) => {- onChange({- field: "description",- value: JSON.stringify(evaluatedValue ?? ""),- });- }}- />- <InputErrorsTooltip errors={errors.description}>- <TextArea- color={errors.description ? "error" : undefined}- id={fieldIds.description}- name="description"- disabled={isLiteralExpression(values.description) === false}- value={description}- onChange={(value) => {- onChange({- field: "description",- value: JSON.stringify(value),- });- }}- autoGrow- maxRows={10}- />- </InputErrorsTooltip>- </BindingControl>- <BindingControl>- <Grid- flow={"column"}- gap={1}- justify={"start"}- align={"center"}- css={{ py: theme.spacing[2] }}- >- <BindingPopover- scope={scope}- aliases={aliases}- variant={- isLiteralExpression(values.excludePageFromSearch)- ? "default"- : "bound"- }- value={values.excludePageFromSearch}- onChange={(value) => {- onChange({- field: "excludePageFromSearch",- value,- });- }}- onRemove={(evaluatedValue) => {- onChange({- field: "excludePageFromSearch",- value: JSON.stringify(evaluatedValue ?? ""),- });- }}- />- <Checkbox- id={fieldIds.excludePageFromSearch}- disabled={- isLiteralExpression(values.excludePageFromSearch) ===- false- }- checked={excludePageFromSearch}- onCheckedChange={() => {- const newValue = !excludePageFromSearch;- onChange({- field: "excludePageFromSearch",- value: newValue.toString(),- });- }}- />-- <InputErrorsTooltip errors={errors.excludePageFromSearch}>- <Label htmlFor={fieldIds.excludePageFromSearch}>- Exclude this page from search results- </Label>- </InputErrorsTooltip>- </Grid>- </BindingControl>- </Grid>-- <LanguageField- errors={errors.language}- value={values.language}- onChange={(value) => onChange({ field: "language", value })}- />- </Grid>-- <Separator />-- {/**- * ----------------------========<<<Social Sharing>>>>========----------------------- */}- <Grid gap={2} css={{ my: theme.spacing[5], mx: theme.spacing[8] }}>- <Label htmlFor={fieldIds.socialImageAssetId} text="title">- Social Image- </Label>- <Text color="subtle">- This image appears when you share a link to this page on social- media sites. If no image is set here, the Social Image set in the- project settings will be used. The optimal dimensions for the- image are 1200x630 px or larger with a 1.91:1 aspect ratio.- </Text>- <BindingControl>- <BindingPopover- scope={scope}- aliases={aliases}- variant={- isLiteralExpression(values.socialImageUrl)- ? "default"- : "bound"- }- value={values.socialImageUrl}- onChange={(value) => {- onChange({- field: "socialImageUrl",- value,- });- }}- onRemove={(evaluatedValue) => {- onChange({- field: "socialImageUrl",- value: JSON.stringify(evaluatedValue ?? ""),- });- }}- />- <InputErrorsTooltip errors={errors.socialImageUrl}>- <InputField- placeholder="https://www.url.com"- disabled={- isLiteralExpression(values.socialImageUrl) === false- }- color={errors.socialImageUrl && "error"}- value={socialImageUrl}- onChange={(event) => {- onChange({- field: "socialImageUrl",- value: JSON.stringify(event.target.value),- });- onChange({ field: "socialImageAssetId", value: "" });- }}- />- </InputErrorsTooltip>- </BindingControl>- <Grid gap={1} flow={"column"}>- <ImageControl- onAssetIdChange={(socialImageAssetId) => {- onChange({- field: "socialImageAssetId",- value: socialImageAssetId,- });- onChange({ field: "socialImageUrl", value: "" });- }}- >- <Button- id={fieldIds.socialImageAssetId}- css={{ justifySelf: "start" }}- color="neutral"- >- Choose Image From Assets- </Button>- </ImageControl>- </Grid>-- {socialImageAsset?.type === "image" && (- <ImageInfo- asset={socialImageAsset}- onDelete={() => {- onChange({- field: "socialImageAssetId",- value: "",- });- }}- />- )}- <div />- <SocialPreview- ogImageUrl={- socialImageAsset?.type === "image"- ? socialImageAsset.name- : socialImageUrl- }- ogUrl={pageUrl}- ogTitle={title}- ogDescription={description}- />- </Grid>-- <Separator />-- <InputErrorsTooltip errors={errors.customMetas}>- <div>- <CustomMetadata- customMetas={values.customMetas}- onChange={(customMetas) => {- onChange({- field: "customMetas",- value: customMetas,- });- }}- />- </div>- </InputErrorsTooltip>- </fieldset>-- {(project?.marketplaceApprovalStatus === "PENDING" ||- project?.marketplaceApprovalStatus === "APPROVED" ||- project?.marketplaceApprovalStatus === "REJECTED") && (- <>- <Separator />- <MarketplaceSection values={values} onChange={onChange} />- </>- )}-- <Box css={{ height: theme.spacing[10] }} />- </ScrollArea>- </Grid>- );-};--const nameToPath = (pages: Pages | undefined, name: string) => {- if (name === "") {- return "";- }-- const slug = slugify(name, { lower: true, strict: true });- const path = `/${slug}`;-- // for TypeScript- if (pages === undefined) {- return path;- }-- if (findPageByIdOrPath(path, pages) === undefined) {- return path;- }-- let suffix = 1;-- while (findPageByIdOrPath(`${path}${suffix}`, pages) !== undefined) {- suffix++;- }-- return `${path}${suffix}`;-};--export const NewPageSettings = ({- onClose,- onSuccess,-}: {- onClose: () => void;- onSuccess: (pageId: Page["id"]) => void;-}) => {- const pages = useStore($pages);-- const [values, setValues] = useState<Values>({- ...fieldDefaultValues,- parentFolderId: pages?.rootFolderId ?? fieldDefaultValues.parentFolderId,- path: nameToPath(pages, fieldDefaultValues.name),- });- const { variableValues } = useStore($pageRootScope);- const errors = validateValues(pages, undefined, values, variableValues);-- const handleSubmit = () => {- if (Object.keys(errors).length === 0) {- const pageId = nanoid();- createPage(pageId, values);- updatePage(pageId, values);- onSuccess(pageId);- }- };-- return (- <NewPageSettingsView- onSubmit={handleSubmit}- onClose={onClose}- isSubmitting={false}- >- <FormFields- autoSelect- errors={errors}- values={values}- onChange={(val) => {- setValues((values) => {- const changes = { [val.field]: val.value };-- if (val.field === "name") {- if (values.path === nameToPath(pages, values.name)) {- changes.path = nameToPath(pages, val.value);- }- if (values.title === values.name) {- changes.title = val.value;- }- }- return { ...values, ...changes };- });- }}- />- </NewPageSettingsView>- );-};--const NewPageSettingsView = ({- onSubmit,- isSubmitting,- children,-}: {- onSubmit: () => void;- isSubmitting: boolean;- onClose: () => void;- children: JSX.Element;-}) => {- return (- <>- <DialogTitle- suffix={- <DialogTitleActions>- <TitleSuffixSpacer />- <Button- state={isSubmitting ? "pending" : "auto"}- onClick={onSubmit}- tabIndex={2}- >- {isSubmitting ? "Creating" : "Create page"}- </Button>- <DialogClose />- </DialogTitleActions>- }- >- New Page Settings- </DialogTitle>- <Form onSubmit={onSubmit}>{children}</Form>- </>- );-};--const createPage = (pageId: Page["id"], values: Values) => {- serverSyncStore.createTransaction(- [$pages, $instances],- (pages, instances) => {- if (pages === undefined) {- return;- }- const rootInstanceId = nanoid();- pages.pages.set(pageId, {- id: pageId,- name: values.name,- path: values.path,- title: values.title,- rootInstanceId,- meta: {},- });- instances.set(rootInstanceId, {- type: "instance",- id: rootInstanceId,- component: elementComponent,- tag: "body",- children: [],- });- registerFolderChildMutable(pages, pageId, values.parentFolderId);- selectInstance(undefined);- }- );-};--const updatePage = (pageId: Page["id"], values: Partial<Values>) => {- const updatePageMutable = (- page: Page,- values: Partial<Values>,- pages: Pages- ) => {- if (values.name !== undefined) {- page.name = values.name;- }- if (values.path !== undefined) {- page.path = page.id === pages.homePageId ? "" : values.path;- }- if (values.title !== undefined) {- page.title = values.title;- }-- if (values.description !== undefined) {- page.meta.description = values.description;- }-- if (values.excludePageFromSearch !== undefined) {- page.meta.excludePageFromSearch = values.excludePageFromSearch;- }-- if (values.language !== undefined) {- page.meta.language =- values.language.length > 0 ? values.language : undefined;- }-- if ("status" in values) {- page.meta.status = values.status;- }-- if (values.redirect !== undefined) {- page.meta.redirect =- values.redirect.length > 0 ? values.redirect : undefined;- }-- if (values.socialImageAssetId !== undefined) {- page.meta.socialImageAssetId =- values.socialImageAssetId.length > 0- ? values.socialImageAssetId- : undefined;- }- if (values.socialImageUrl !== undefined) {- page.meta.socialImageUrl =- values.socialImageUrl.length > 0 ? values.socialImageUrl : undefined;- }-- if (values.customMetas !== undefined) {- page.meta.custom = values.customMetas;- }-- if (values.documentType !== undefined) {- page.meta.documentType = values.documentType;- }-- if (values.parentFolderId !== undefined) {- registerFolderChildMutable(pages, page.id, values.parentFolderId);- }-- if (values.marketplaceInclude !== undefined) {- page.marketplace ??= {};- page.marketplace.include = values.marketplaceInclude;- }- if (values.marketplaceCategory !== undefined) {- page.marketplace ??= {};- page.marketplace.category =- values.marketplaceCategory.length > 0- ? values.marketplaceCategory- : undefined;- }- if (values.marketplaceThumbnailAssetId !== undefined) {- page.marketplace ??= {};- page.marketplace.thumbnailAssetId =- values.marketplaceThumbnailAssetId.length > 0- ? values.marketplaceThumbnailAssetId- : undefined;- }- };-- serverSyncStore.createTransaction([$pages], (pages) => {- if (pages === undefined) {- return;- }-- const pageToUpdate = pages.pages.get(pageId);-- if (pageToUpdate !== undefined) {- updatePageMutable(pageToUpdate, values, pages);- }-- // swap home page- if (values.isHomePage && pages.homePageId !== pageId) {- const newHomePage = pages.pages.get(pageId);- const oldHomePage = getHomePage(pages);- if (newHomePage === undefined) {- throw new Error(`Page with id ${pageId} not found`);- }-- pages.homePageId = newHomePage.id;- newHomePage.path = "";- newHomePage.name = "Home";-- // For simplicity skip logic in case of names are same i.e. Old Home 1, Old Home 2- oldHomePage.name = "Old Home";- oldHomePage.path = nameToPath(pages, oldHomePage.name);-- const rootFolder = pages.folders.get(pages.rootFolderId);-- if (rootFolder === undefined) {- throw new Error("Root folder not found");- }-- cleanupChildRefsMutable(newHomePage.id, pages.folders);- rootFolder.children.unshift(newHomePage.id);- }- });-};--export const PageSettings = ({- onClose,- onDuplicate,- onDelete,- pageId,-}: {- onClose: () => void;- onDuplicate: (newPageId: string) => void;- onDelete?: () => void;- pageId: string;-}) => {- const pages = useStore($pages);- const page = pages && findPageByIdOrPath(pageId, pages);-- const isHomePage = page?.id === pages?.homePageId;-- const [unsavedValues, setUnsavedValues] = useState<Partial<Values>>({});-- const values: Values = {- ...(page ? toFormValues(page, pages, isHomePage) : fieldDefaultValues),- ...unsavedValues,- };-- const { variableValues } = useStore($pageRootScope);- const errors = validateValues(pages, pageId, values, variableValues);-- const debouncedFn = useEffectEvent(() => {- if (- Object.keys(unsavedValues).length === 0 ||- Object.keys(errors).length !== 0- ) {- return;- }-- updatePage(pageId, unsavedValues);-- setUnsavedValues({});- });-- const handleSubmitDebounced = useDebouncedCallback(debouncedFn, 1000);-- const [refreshDebounce, setRefreshDebounce] = useState(0);-- useEffect(() => {- // we can't flush immediately as setState haven't propagated at that time- handleSubmitDebounced.flush();- }, [refreshDebounce, handleSubmitDebounced]);-- const handleChange = useCallback(- <Name extends FieldName>(event: { field: Name; value: Values[Name] }) => {- setUnsavedValues((values) => ({- ...values,- [event.field]: event.value,- }));- handleSubmitDebounced();-- if (event.field === "isHomePage") {- setRefreshDebounce((prev) => prev + 1);- }- },- [handleSubmitDebounced]- );-- useUnmount(() => {- if (- Object.keys(unsavedValues).length === 0 ||- Object.keys(errors).length !== 0- ) {- return;- }- updatePage(pageId, unsavedValues);- });-- const handleRequestDelete = () => {- if (onDelete) {- onDelete();- }- };-- if (page === undefined) {- return null;- }-- return (- <>- <PageSettingsView- onClose={onClose}- onDelete={values.isHomePage === false ? handleRequestDelete : undefined}- onDuplicate={() => {- const newPageId = duplicatePage(pageId);- if (newPageId !== undefined) {- // In `canvas.tsx`, within `subscribeStyles`, we use `requestAnimationFrame` (RAF) for style recalculation.- // After `duplicatePage`, styles are not yet recalculated.- // To ensure they are properly updated, we use double RAF.- requestAnimationFrame(() => {- // At this tick styles are updating- requestAnimationFrame(() => {- // At this tick styles are updated- onDuplicate(newPageId);- });- });- }- }}- >- <FormFields errors={errors} values={values} onChange={handleChange} />- </PageSettingsView>- </>- );-};--const PageSettingsView = ({- onDelete,- onDuplicate,- onClose,- children,-}: {- onDelete?: () => void;- onDuplicate: () => void;- onClose: () => void;- children: JSX.Element;-}) => {- const isDesignMode = useStore($isDesignMode);- const containerRef = useRef<HTMLFormElement>(null);- return (- <>- <DialogTitle- suffix={- <DialogTitleActions>- {isDesignMode && onDelete && (- <Tooltip content="Delete page" side="bottom">- <Button- color="ghost"- prefix={<TrashIcon />}- onClick={onDelete}- aria-label="Delete page"- tabIndex={2}- />- </Tooltip>- )}- {isDesignMode && (- <Tooltip content="Duplicate page" side="bottom">- <Button- color="ghost"- prefix={<CopyIcon />}- onClick={onDuplicate}- aria-label="Duplicate page"- tabIndex={2}- />- </Tooltip>- )}- <DialogClose />- </DialogTitleActions>- }- >- Page Settings- </DialogTitle>- <Form onSubmit={onClose} ref={containerRef} data-floating-panel-container>- <fieldset style={{ display: "contents" }} disabled={!isDesignMode}>- {children}- </fieldset>- </Form>- </>- );-};diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts b/apps/builder/app/builder/features/pages/page-settings/page-settings.test.tsnew file mode 100644index 0000000000..e37dc800f1--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts@@ -0,0 +1,221 @@+import { describe, expect, test, vi } from "vitest";+import type { Folder, Page, Pages } from "@webstudio-is/sdk";+import { ROOT_FOLDER_ID } from "@webstudio-is/sdk";+import type { Values } from "./shared";++const mocks = vi.hoisted(() => ({+ isPathAvailable: vi.fn(() => true),+}));++vi.mock("../page-utils", () => ({+ registerFolderChildMutable: () => undefined,+ cleanupChildRefsMutable: () => undefined,+ duplicatePage: () => undefined,+ isPathAvailable: mocks.isPathAvailable,+ $pageRootScope: {+ get: () => ({ variableValues: new Map(), scope: {}, aliases: new Map() }),+ subscribe: () => () => undefined,+ },+}));++const { __testing__ } = await import("./page-settings");++const {+ computePagePath,+ fieldDefaultValues,+ getAuthFromValues,+ toFormValues,+ validateValues,+} = __testing__;++const homePage: Page = {+ id: "home",+ name: "Home",+ path: "",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "home-root",+};++const createPage = (page: Partial<Page> & Pick<Page, "id">): Page => ({+ name: page.id,+ path: `/${page.id}`,+ title: `"${page.id}"`,+ meta: {},+ rootInstanceId: `${page.id}-root`,+ ...page,+});++const createFolder = (+ folder: Partial<Folder> & Pick<Folder, "id">+): Folder => ({+ name: folder.id,+ slug: folder.id,+ children: [],+ ...folder,+});++const createPages = ({+ pages = [homePage],+ folders,+}: {+ pages?: Page[];+ folders?: Folder[];+} = {}): Pages => ({+ homePageId: homePage.id,+ rootFolderId: ROOT_FOLDER_ID,+ pages: new Map(pages.map((page) => [page.id, page])),+ folders: new Map(+ (+ folders ?? [+ createFolder({+ id: ROOT_FOLDER_ID,+ name: "Root",+ slug: "",+ children: pages.map((page) => page.id),+ }),+ ]+ ).map((folder) => [folder.id, folder])+ ),+});++const createValues = (values: Partial<Values> = {}): Values => ({+ ...fieldDefaultValues,+ auth: { ...fieldDefaultValues.auth },+ customMetas: [...fieldDefaultValues.customMetas],+ marketplace: { ...fieldDefaultValues.marketplace },+ ...values,+});++describe("computePagePath", () => {+ test("returns root path for the home page", () => {+ const pages = createPages();+ expect(computePagePath(createValues({ isHomePage: true }), pages)).toBe(+ "/"+ );+ });++ test("combines parent folder path with page path", () => {+ const page = createPage({ id: "post", path: "/post" });+ const pages = createPages({+ pages: [homePage, page],+ folders: [+ createFolder({+ id: ROOT_FOLDER_ID,+ name: "Root",+ slug: "",+ children: ["blog"],+ }),+ createFolder({+ id: "blog",+ slug: "blog",+ children: [page.id],+ }),+ ],+ });++ expect(+ computePagePath(+ createValues({ parentFolderId: "blog", path: "/post" }),+ pages+ )+ ).toBe("/blog/post");+ });+});++describe("validateValues", () => {+ test("accumulates duplicate path errors from the general section", () => {+ mocks.isPathAvailable.mockReturnValueOnce(false);++ const errors = validateValues(+ createPages(),+ "page-id",+ createValues({+ path: "/taken",+ }),+ new Map()+ );++ expect(errors.path).toEqual(["All paths must be unique"]);+ });++ test("accumulates auth errors with other field errors", () => {+ const errors = validateValues(+ createPages(),+ undefined,+ createValues({+ path: "missing-leading-slash",+ auth: {+ login: "admin:root",+ password: "secret phrase",+ },+ }),+ new Map()+ );++ expect(errors.path).toEqual(+ expect.arrayContaining([+ "Must start with a / or a full URL e.g. https://website.org",+ ])+ );+ expect(errors.auth).toEqual({+ login: ["Login can't contain a colon"],+ password: ["Password can't contain whitespace"],+ });+ });++ test("does not require auth when both credentials are empty", () => {+ expect(+ validateValues(createPages(), undefined, createValues(), new Map()).auth+ ).toBeUndefined();+ });+});++describe("auth form values", () => {+ test("serializes valid auth and omits empty or invalid auth", () => {+ expect(getAuthFromValues(createValues())).toBeUndefined();+ expect(+ getAuthFromValues(+ createValues({+ auth: {+ login: "admin",+ password: "secret",+ },+ })+ )+ ).toEqual({+ method: "basic",+ login: "admin",+ password: "secret",+ });+ expect(+ getAuthFromValues(+ createValues({+ auth: {+ login: "admin:root",+ password: "secret",+ },+ })+ )+ ).toBeUndefined();+ });++ test("maps page auth metadata into form values", () => {+ const page = createPage({+ id: "private",+ meta: {+ auth: {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ },+ });+ const pages = createPages({ pages: [homePage, page] });++ expect(toFormValues(page, pages, false).auth).toEqual({+ login: "admin",+ password: "secret",+ });+ });+});diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsxnew file mode 100644index 0000000000..47a5aa9f67--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx@@ -0,0 +1,767 @@+import { nanoid } from "nanoid";+import { useState, useCallback, useEffect, type JSX, useRef } from "react";+import { useStore } from "@nanostores/react";+import { useDebouncedCallback } from "use-debounce";+import slugify from "slugify";+import {+ ROOT_FOLDER_ID,+ documentTypes,+ type Page,+ type Pages,+ findPageByIdOrPath,+ findParentFolderByChildId,+ getPagePath,+ getHomePage,+ elementComponent,+} from "@webstudio-is/sdk";+import { validateBasicAuth } from "@webstudio-is/wsauth";+import {+ theme,+ Button,+ Box,+ Tooltip,+ Grid,+ Text,+ ScrollArea,+ Link,+ PanelBanner,+ css,+ TitleSuffixSpacer,+ DialogClose,+ DialogTitle,+ DialogTitleActions,+} from "@webstudio-is/design-system";+import { CopyIcon, TrashIcon } from "@webstudio-is/icons";+import { $isDesignMode, $permissions } from "~/shared/nano-states";+import { $project } from "~/shared/sync/data-stores";+import { $openProjectSettings } from "~/shared/nano-states/project-settings";+import { $instances, $pages } from "~/shared/sync/data-stores";+import { serverSyncStore } from "~/shared/sync/sync-stores";+import { useEffectEvent } from "~/shared/hook-utils/effect-event";+import { useUnmount } from "~/shared/hook-utils/use-mount";+import { selectInstance } from "~/shared/nano-states";+import {+ registerFolderChildMutable,+ cleanupChildRefsMutable,+ $pageRootScope,+ duplicatePage,+} from "../page-utils";+import { CollapsibleSection } from "~/builder/shared/collapsible-section";+import { Form } from "../form";+import { findMatchingRedirect } from "~/shared/project-settings/utils";+import { AuthSection, validateAuthSection } from "./section-auth";+import {+ CustomMetadataSection,+ validateCustomMetadataSection,+} from "./section-custom-metadata";+import { GeneralSection, validateGeneralSection } from "./section-general";+import { MarketplaceSection } from "./section-marketplace";+import { SearchSection, validateSearchSection } from "./section-search";+import {+ SocialImageSection,+ validateSocialImageSection,+} from "./section-social-image";+import {+ type Errors,+ type FieldName,+ type OnChange,+ type Values,+} from "./shared";++const fieldDefaultValues: Values = {+ name: "Untitled",+ parentFolderId: ROOT_FOLDER_ID,+ path: "/untitled",+ isHomePage: false,+ title: `"Untitled"`,+ description: `""`,+ excludePageFromSearch: `true`,+ language: `""`,+ socialImageUrl: `""`,+ socialImageAssetId: "",+ status: undefined,+ redirect: `""`,+ documentType: "html" as (typeof documentTypes)[number],+ auth: {+ login: "",+ password: "",+ },+ customMetas: [{ property: "", content: `""` }],+ marketplace: {+ include: false,+ category: "",+ thumbnailAssetId: "",+ },+};++const computePagePath = (values: Values, pages: Pages): string => {+ if (values.isHomePage) {+ return "/";+ }+ const foldersPath = getPagePath(values.parentFolderId, pages);+ return [foldersPath, values.path]+ .filter(Boolean)+ .join("/")+ .replace(/\/+/g, "/");+};++const nonAuthFieldNames = Object.keys(fieldDefaultValues).filter(+ (fieldName): fieldName is Exclude<FieldName, "auth"> => fieldName !== "auth"+);++const validateValues = (+ pages: undefined | Pages,+ // undefined page id means new page+ pageId: undefined | Page["id"],+ values: Values,+ variableValues: Map<string, unknown>+): Errors => {+ const errors: Errors = {};+ const sectionErrors = [+ validateGeneralSection({ pages, pageId, values, variableValues }),+ validateAuthSection(values),+ validateSearchSection(values, variableValues),+ validateSocialImageSection(values, variableValues),+ validateCustomMetadataSection(values, variableValues),+ ];+ for (const sectionError of sectionErrors) {+ if (sectionError.auth) {+ errors.auth = { ...errors.auth, ...sectionError.auth };+ }+ for (const fieldName of nonAuthFieldNames) {+ const messages = sectionError[fieldName];+ if (messages === undefined) {+ continue;+ }+ errors[fieldName] = [...(errors[fieldName] ?? []), ...messages];+ }+ }+ return errors;+};++const toFormValues = (+ page: Page,+ pages: Pages,+ isHomePage: boolean+): Values => {+ const parentFolder = findParentFolderByChildId(page.id, pages.folders);+ return {+ name: page.name,+ parentFolderId: parentFolder?.id ?? pages.rootFolderId,+ path: page.path,+ title: page.title,+ description: page.meta.description ?? fieldDefaultValues.description,+ socialImageUrl:+ page.meta.socialImageUrl ?? fieldDefaultValues.socialImageUrl,+ socialImageAssetId:+ page.meta.socialImageAssetId ?? fieldDefaultValues.socialImageAssetId,+ excludePageFromSearch:+ page.meta.excludePageFromSearch ??+ fieldDefaultValues.excludePageFromSearch,+ language: page.meta.language ?? fieldDefaultValues.language,+ status: page.meta.status ?? fieldDefaultValues.status,+ redirect: page.meta.redirect ?? fieldDefaultValues.redirect,+ documentType: page.meta.documentType ?? fieldDefaultValues.documentType,+ auth: {+ login: page.meta.auth?.login ?? fieldDefaultValues.auth.login,+ password: page.meta.auth?.password ?? fieldDefaultValues.auth.password,+ },+ isHomePage,+ customMetas: page.meta.custom ?? fieldDefaultValues.customMetas,+ marketplace: {+ include:+ page.marketplace?.include ?? fieldDefaultValues.marketplace.include,+ category:+ page.marketplace?.category ?? fieldDefaultValues.marketplace.category,+ thumbnailAssetId:+ page.marketplace?.thumbnailAssetId ??+ fieldDefaultValues.marketplace.thumbnailAssetId,+ },+ };+};++const getAuthFromValues = (values: Values): Page["meta"]["auth"] => {+ if (values.auth.login === "" && values.auth.password === "") {+ return;+ }+ const auth = validateBasicAuth({+ login: values.auth.login,+ password: values.auth.password,+ }).auth;+ if (auth === undefined) {+ return;+ }+ return {+ method: auth.method,+ login: auth.login,+ password: auth.password,+ };+};++export const __testing__ = {+ computePagePath,+ fieldDefaultValues,+ getAuthFromValues,+ toFormValues,+ validateValues,+};++const fieldsetStyle = css({+ all: "unset",+ display: "block",+ "&:disabled": {+ opacity: 0.4,+ },+});++const FormFields = ({+ autoSelect,+ errors,+ values,+ onChange,+ showAuthErrors,+}: {+ autoSelect?: boolean;+ errors: Errors;+ values: Values;+ onChange: OnChange;+ showAuthErrors?: boolean;+}) => {+ const project = useStore($project);+ const pages = useStore($pages);+ const { allowAuth } = useStore($permissions);++ if (pages === undefined) {+ return;+ }++ const fullPagePath = computePagePath(values, pages);+ const matchingRedirect = findMatchingRedirect(+ fullPagePath,+ pages.redirects ?? []+ );++ return (+ <Grid css={{ height: "100%" }}>+ <ScrollArea>+ {matchingRedirect && (+ <PanelBanner variant="warning">+ <Text>+ A redirect from "{matchingRedirect.old}" will override this page.+ The page will not be rendered when published.{" "}+ <Link+ color="inherit"+ underline="always"+ onClick={() => {+ $openProjectSettings.set("redirects");+ }}+ >+ Go to Redirects settings+ </Link>+ </Text>+ </PanelBanner>+ )}+ <CollapsibleSection label="General">+ <GeneralSection+ autoSelect={autoSelect}+ errors={errors}+ values={values}+ pages={pages}+ onChange={onChange}+ />+ </CollapsibleSection>++ <CollapsibleSection label="Authentication">+ <AuthSection+ values={values}+ errors={errors}+ onChange={onChange}+ showUpgrade={allowAuth === false}+ showErrors={showAuthErrors}+ />+ </CollapsibleSection>++ {/**+ * ----------------------========<<<Search Results>>>>========----------------------+ */}+ <CollapsibleSection label="Search">+ <fieldset+ disabled={values.documentType === "xml"}+ className={fieldsetStyle()}+ >+ <SearchSection+ values={values}+ errors={errors}+ onChange={onChange}+ />+ </fieldset>+ </CollapsibleSection>++ <CollapsibleSection label="Social Image">+ <fieldset+ disabled={values.documentType === "xml"}+ className={fieldsetStyle()}+ >+ <SocialImageSection+ values={values}+ errors={errors}+ onChange={onChange}+ />+ </fieldset>+ </CollapsibleSection>++ <CollapsibleSection label="Custom Metadata">+ <fieldset+ disabled={values.documentType === "xml"}+ className={fieldsetStyle()}+ >+ <CustomMetadataSection+ values={values}+ errors={errors}+ onChange={onChange}+ />+ </fieldset>+ </CollapsibleSection>++ {(project?.marketplaceApprovalStatus === "PENDING" ||+ project?.marketplaceApprovalStatus === "APPROVED" ||+ project?.marketplaceApprovalStatus === "REJECTED") && (+ <CollapsibleSection label="Marketplace">+ <MarketplaceSection values={values} onChange={onChange} />+ </CollapsibleSection>+ )}++ <Box css={{ height: theme.spacing[10] }} />+ </ScrollArea>+ </Grid>+ );+};++const nameToPath = (pages: Pages | undefined, name: string) => {+ if (name === "") {+ return "";+ }++ const slug = slugify(name, { lower: true, strict: true });+ const path = `/${slug}`;++ // for TypeScript+ if (pages === undefined) {+ return path;+ }++ if (findPageByIdOrPath(path, pages) === undefined) {+ return path;+ }++ let suffix = 1;++ while (findPageByIdOrPath(`${path}${suffix}`, pages) !== undefined) {+ suffix++;+ }++ return `${path}${suffix}`;+};++export const NewPageSettings = ({+ onSuccess,+}: {+ onSuccess: (pageId: Page["id"]) => void;+}) => {+ const pages = useStore($pages);++ const [values, setValues] = useState<Values>({+ ...fieldDefaultValues,+ parentFolderId: pages?.rootFolderId ?? fieldDefaultValues.parentFolderId,+ path: nameToPath(pages, fieldDefaultValues.name),+ });+ const [isSubmitAttempted, setIsSubmitAttempted] = useState(false);+ const { variableValues } = useStore($pageRootScope);+ const errors = validateValues(pages, undefined, values, variableValues);++ const handleSubmit = () => {+ setIsSubmitAttempted(true);+ if (Object.keys(errors).length === 0) {+ const pageId = nanoid();+ createPage(pageId, values);+ updatePage(pageId, values);+ onSuccess(pageId);+ }+ };++ return (+ <NewPageSettingsView onSubmit={handleSubmit} isSubmitting={false}>+ <FormFields+ autoSelect+ errors={errors}+ values={values}+ showAuthErrors={isSubmitAttempted}+ onChange={(val) => {+ setValues((values) => {+ const changes = { [val.field]: val.value };++ if (val.field === "name") {+ if (values.path === nameToPath(pages, values.name)) {+ changes.path = nameToPath(pages, val.value);+ }+ if (values.title === values.name) {+ changes.title = val.value;+ }+ }+ return { ...values, ...changes };+ });+ }}+ />+ </NewPageSettingsView>+ );+};++const NewPageSettingsView = ({+ onSubmit,+ isSubmitting,+ children,+}: {+ onSubmit: () => void;+ isSubmitting: boolean;+ children: JSX.Element;+}) => {+ return (+ <>+ <DialogTitle+ suffix={+ <DialogTitleActions>+ <TitleSuffixSpacer />+ <Button+ state={isSubmitting ? "pending" : "auto"}+ onClick={onSubmit}+ tabIndex={2}+ >+ {isSubmitting ? "Creating" : "Create page"}+ </Button>+ <DialogClose />+ </DialogTitleActions>+ }+ >+ New Page Settings+ </DialogTitle>+ <Form onSubmit={onSubmit}>{children}</Form>+ </>+ );+};++const createPage = (pageId: Page["id"], values: Values) => {+ serverSyncStore.createTransaction(+ [$pages, $instances],+ (pages, instances) => {+ if (pages === undefined) {+ return;+ }+ const rootInstanceId = nanoid();+ pages.pages.set(pageId, {+ id: pageId,+ name: values.name,+ path: values.path,+ title: values.title,+ rootInstanceId,+ meta: {+ auth: getAuthFromValues(values),+ },+ });+ instances.set(rootInstanceId, {+ type: "instance",+ id: rootInstanceId,+ component: elementComponent,+ tag: "body",+ children: [],+ });+ registerFolderChildMutable(pages, pageId, values.parentFolderId);+ selectInstance(undefined);+ }+ );+};++const updatePage = (pageId: Page["id"], values: Partial<Values>) => {+ const updatePageMutable = (+ page: Page,+ values: Partial<Values>,+ pages: Pages+ ) => {+ if (values.name !== undefined) {+ page.name = values.name;+ }+ if (values.path !== undefined) {+ page.path = page.id === pages.homePageId ? "" : values.path;+ }+ if (values.title !== undefined) {+ page.title = values.title;+ }++ if (values.description !== undefined) {+ page.meta.description = values.description;+ }++ if (values.excludePageFromSearch !== undefined) {+ page.meta.excludePageFromSearch = values.excludePageFromSearch;+ }++ if (values.language !== undefined) {+ page.meta.language =+ values.language.length > 0 ? values.language : undefined;+ }++ if ("status" in values) {+ page.meta.status = values.status;+ }++ if (values.redirect !== undefined) {+ page.meta.redirect =+ values.redirect.length > 0 ? values.redirect : undefined;+ }++ if (values.socialImageAssetId !== undefined) {+ page.meta.socialImageAssetId =+ values.socialImageAssetId.length > 0+ ? values.socialImageAssetId+ : undefined;+ }+ if (values.socialImageUrl !== undefined) {+ page.meta.socialImageUrl =+ values.socialImageUrl.length > 0 ? values.socialImageUrl : undefined;+ }++ if (values.customMetas !== undefined) {+ page.meta.custom = values.customMetas;+ }++ if (values.documentType !== undefined) {+ page.meta.documentType = values.documentType;+ }++ if (values.auth !== undefined) {+ page.meta.auth = getAuthFromValues({+ ...toFormValues(page, pages, page.id === pages.homePageId),+ ...values,+ });+ }++ if (values.parentFolderId !== undefined) {+ registerFolderChildMutable(pages, page.id, values.parentFolderId);+ }++ if (values.marketplace !== undefined) {+ page.marketplace ??= {};+ page.marketplace.include = values.marketplace.include;+ page.marketplace.category =+ values.marketplace.category.length > 0+ ? values.marketplace.category+ : undefined;+ page.marketplace.thumbnailAssetId =+ values.marketplace.thumbnailAssetId.length > 0+ ? values.marketplace.thumbnailAssetId+ : undefined;+ }+ };++ serverSyncStore.createTransaction([$pages], (pages) => {+ if (pages === undefined) {+ return;+ }++ const pageToUpdate = pages.pages.get(pageId);++ if (pageToUpdate !== undefined) {+ updatePageMutable(pageToUpdate, values, pages);+ }++ // swap home page+ if (values.isHomePage && pages.homePageId !== pageId) {+ const newHomePage = pages.pages.get(pageId);+ const oldHomePage = getHomePage(pages);+ if (newHomePage === undefined) {+ throw new Error(`Page with id ${pageId} not found`);+ }++ pages.homePageId = newHomePage.id;+ newHomePage.path = "";+ newHomePage.name = "Home";++ // For simplicity skip logic in case of names are same i.e. Old Home 1, Old Home 2+ oldHomePage.name = "Old Home";+ oldHomePage.path = nameToPath(pages, oldHomePage.name);++ const rootFolder = pages.folders.get(pages.rootFolderId);++ if (rootFolder === undefined) {+ throw new Error("Root folder not found");+ }++ cleanupChildRefsMutable(newHomePage.id, pages.folders);+ rootFolder.children.unshift(newHomePage.id);+ }+ });+};++export const PageSettings = ({+ onClose,+ onDuplicate,+ onDelete,+ pageId,+}: {+ onClose: () => void;+ onDuplicate: (newPageId: string) => void;+ onDelete?: () => void;+ pageId: string;+}) => {+ const pages = useStore($pages);+ const page = pages && findPageByIdOrPath(pageId, pages);++ const isHomePage = page?.id === pages?.homePageId;++ const [unsavedValues, setUnsavedValues] = useState<Partial<Values>>({});++ const values: Values = {+ ...(page ? toFormValues(page, pages, isHomePage) : fieldDefaultValues),+ ...unsavedValues,+ };++ const { variableValues } = useStore($pageRootScope);+ const errors = validateValues(pages, pageId, values, variableValues);++ const debouncedFn = useEffectEvent(() => {+ if (+ Object.keys(unsavedValues).length === 0 ||+ Object.keys(errors).length !== 0+ ) {+ return;+ }++ updatePage(pageId, unsavedValues);++ setUnsavedValues({});+ });++ const handleSubmitDebounced = useDebouncedCallback(debouncedFn, 1000);++ const [refreshDebounce, setRefreshDebounce] = useState(0);++ useEffect(() => {+ // we can't flush immediately as setState haven't propagated at that time+ handleSubmitDebounced.flush();+ }, [refreshDebounce, handleSubmitDebounced]);++ const handleChange = useCallback(+ <Name extends FieldName>(event: { field: Name; value: Values[Name] }) => {+ setUnsavedValues((values) => ({+ ...values,+ [event.field]: event.value,+ }));+ handleSubmitDebounced();++ if (event.field === "isHomePage") {+ setRefreshDebounce((prev) => prev + 1);+ }+ },+ [handleSubmitDebounced]+ );++ useUnmount(() => {+ if (+ Object.keys(unsavedValues).length === 0 ||+ Object.keys(errors).length !== 0+ ) {+ return;+ }+ updatePage(pageId, unsavedValues);+ });++ const handleRequestDelete = () => {+ if (onDelete) {+ onDelete();+ }+ };++ if (page === undefined) {+ return null;+ }++ return (+ <>+ <PageSettingsView+ onClose={onClose}+ onDelete={values.isHomePage === false ? handleRequestDelete : undefined}+ onDuplicate={() => {+ const newPageId = duplicatePage(pageId);+ if (newPageId !== undefined) {+ // In `canvas.tsx`, within `subscribeStyles`, we use `requestAnimationFrame` (RAF) for style recalculation.+ // After `duplicatePage`, styles are not yet recalculated.+ // To ensure they are properly updated, we use double RAF.+ requestAnimationFrame(() => {+ // At this tick styles are updating+ requestAnimationFrame(() => {+ // At this tick styles are updated+ onDuplicate(newPageId);+ });+ });+ }+ }}+ >+ <FormFields errors={errors} values={values} onChange={handleChange} />+ </PageSettingsView>+ </>+ );+};++const PageSettingsView = ({+ onDelete,+ onDuplicate,+ onClose,+ children,+}: {+ onDelete?: () => void;+ onDuplicate: () => void;+ onClose: () => void;+ children: JSX.Element;+}) => {+ const isDesignMode = useStore($isDesignMode);+ const containerRef = useRef<HTMLFormElement>(null);+ return (+ <>+ <DialogTitle+ suffix={+ <DialogTitleActions>+ {isDesignMode && onDelete && (+ <Tooltip content="Delete page" side="bottom">+ <Button+ color="ghost"+ prefix={<TrashIcon />}+ onClick={onDelete}+ aria-label="Delete page"+ tabIndex={2}+ />+ </Tooltip>+ )}+ {isDesignMode && (+ <Tooltip content="Duplicate page" side="bottom">+ <Button+ color="ghost"+ prefix={<CopyIcon />}+ onClick={onDuplicate}+ aria-label="Duplicate page"+ tabIndex={2}+ />+ </Tooltip>+ )}+ <DialogClose />+ </DialogTitleActions>+ }+ >+ Page Settings+ </DialogTitle>+ <Form onSubmit={onClose} ref={containerRef} data-floating-panel-container>+ <fieldset style={{ display: "contents" }} disabled={!isDesignMode}>+ {children}+ </fieldset>+ </Form>+ </>+ );+};diff --git a/apps/builder/app/builder/features/pages/page-settings/section-auth.tsx b/apps/builder/app/builder/features/pages/page-settings/section-auth.tsxnew file mode 100644index 0000000000..760aad3d92--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/section-auth.tsx@@ -0,0 +1,198 @@+import { useId, useState } from "react";+import {+ Checkbox,+ CheckboxAndLabel,+ Grid,+ InputErrorsTooltip,+ InputField,+ Label,+ Link,+ ProBadge,+ Text,+ Tooltip,+ buttonStyle,+ rawTheme,+ theme,+} from "@webstudio-is/design-system";+import { InfoCircleIcon } from "@webstudio-is/icons";+import { validateBasicAuth } from "@webstudio-is/wsauth";+import type { Errors, OnChange, Values } from "./shared";++const emptyAuth: Values["auth"] = {+ login: "",+ password: "",+};++export const validateAuthSection = (values: Values): Errors => {+ const hasAuth = values.auth.login !== "" || values.auth.password !== "";+ const authErrors = hasAuth+ ? validateBasicAuth({+ login: values.auth.login,+ password: values.auth.password,+ }).errors+ : undefined;+ if (authErrors === undefined) {+ return {};+ }+ return { auth: authErrors };+};++export const AuthSection = ({+ values,+ errors,+ onChange,+ showUpgrade = false,+ showErrors = false,+}: {+ values: Values;+ errors: Errors;+ onChange: OnChange;+ showUpgrade?: boolean;+ showErrors?: boolean;+}) => {+ const enableId = useId();+ const loginId = useId();+ const passwordId = useId();+ const [isExpanded, setIsExpanded] = useState(+ values.auth.login !== "" || values.auth.password !== ""+ );+ const [touchedFields, setTouchedFields] = useState({+ login: false,+ password: false,+ });+ return (+ <Grid gap={2}>+ <Grid gap={1}>+ <CheckboxAndLabel>+ <Checkbox+ id={enableId}+ checked={isExpanded}+ onCheckedChange={(checked) => {+ const nextIsExpanded = checked === true;+ setIsExpanded(nextIsExpanded);+ if (nextIsExpanded === false) {+ setTouchedFields({ login: false, password: false });+ onChange({+ field: "auth",+ value: emptyAuth,+ });+ }+ }}+ />+ <Label htmlFor={enableId}>Require login and password</Label>+ {showUpgrade && <ProBadge>PRO</ProBadge>}+ <Tooltip+ content={+ <>+ <Text>+ Authentication asks visitors for HTTP Basic Auth credentials+ before protected pages load on custom domains.+ </Text>+ {showUpgrade && (+ <>+ <br />+ <Text>+ Page authentication is a Pro feature. You can publish to+ staging for free; upgrade to Pro to publish to custom+ domains.+ </Text>+ <Link+ className={buttonStyle({ color: "gradient" })}+ css={{ marginTop: theme.spacing[5], width: "100%" }}+ color="contrast"+ underline="none"+ target="_blank"+ href="https://webstudio.is/pricing"+ >+ Upgrade+ </Link>+ </>+ )}+ </>+ }+ variant="wrapped"+ >+ <InfoCircleIcon+ color={rawTheme.colors.foregroundSubtle}+ tabIndex={-1}+ />+ </Tooltip>+ </CheckboxAndLabel>+ <Grid gap={1}>+ <Text color="subtle">+ {isExpanded+ ? "Visitors will be asked for HTTP Basic Auth credentials before this page loads."+ : "Anyone can access this page right now."}+ </Text>+ </Grid>+ </Grid>++ {isExpanded && (+ <Grid+ gapX={2}+ gapY={2}+ align="center"+ css={{+ gridTemplateColumns: `auto 1fr`,+ }}+ >+ <Label htmlFor={loginId}>Login</Label>+ <InputErrorsTooltip+ errors={+ showErrors || touchedFields.login ? errors.auth?.login : undefined+ }+ >+ <InputField+ color={+ (showErrors || touchedFields.login) && errors.auth?.login+ ? "error"+ : undefined+ }+ id={loginId}+ value={values.auth.login}+ onChange={(event) => {+ setTouchedFields((touchedFields) => ({+ ...touchedFields,+ login: true,+ }));+ onChange({+ field: "auth",+ value: { ...values.auth, login: event.target.value },+ });+ }}+ />+ </InputErrorsTooltip>+ <Label htmlFor={passwordId}>Password</Label>+ <InputErrorsTooltip+ errors={+ showErrors || touchedFields.password+ ? errors.auth?.password+ : undefined+ }+ >+ <InputField+ color={+ (showErrors || touchedFields.password) && errors.auth?.password+ ? "error"+ : undefined+ }+ id={passwordId}+ type="password"+ value={values.auth.password}+ onChange={(event) => {+ setTouchedFields((touchedFields) => ({+ ...touchedFields,+ password: true,+ }));+ onChange({+ field: "auth",+ value: { ...values.auth, password: event.target.value },+ });+ }}+ />+ </InputErrorsTooltip>+ </Grid>+ )}+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx b/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsxnew file mode 100644index 0000000000..44ad43a360--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx@@ -0,0 +1,55 @@+import { z } from "zod";+import { InputErrorsTooltip } from "@webstudio-is/design-system";+import { CustomMetadata } from "../custom-metadata";+import { computeExpression } from "~/shared/data-variables";+import type { Errors, OnChange, Values } from "./shared";++const CustomMetadataValues = z.object({+ customMetas: z+ .array(+ z.object({+ property: z.string(),+ content: z.string(),+ })+ )+ .optional(),+});++export const validateCustomMetadataSection = (+ values: Values,+ variableValues: Map<string, unknown>+): Errors => {+ const parsedResult = CustomMetadataValues.safeParse({+ customMetas: values.customMetas.map((item) => ({+ property: item.property,+ content: computeExpression(item.content, variableValues),+ })),+ });+ return parsedResult.success ? {} : parsedResult.error.formErrors.fieldErrors;+};++export const CustomMetadataSection = ({+ values,+ errors,+ onChange,+}: {+ values: Values;+ errors: Errors;+ onChange: OnChange;+}) => {+ return (+ <InputErrorsTooltip errors={errors.customMetas}>+ <div>+ <CustomMetadata+ customMetas={values.customMetas}+ onChange={(customMetas) => {+ onChange({+ field: "customMetas",+ value: customMetas,+ });+ }}+ />+ </div>+ </InputErrorsTooltip>+ );+};diff --git a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx b/apps/builder/app/builder/features/pages/page-settings/section-general.tsxnew file mode 100644index 0000000000..c78c677329--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/section-general.tsx@@ -0,0 +1,499 @@+import { type FocusEventHandler, useId } from "react";+import { useStore } from "@nanostores/react";+import { z } from "zod";+import {+ Checkbox,+ Flex,+ Grid,+ InputErrorsTooltip,+ InputField,+ Label,+ Link,+ ProBadge,+ Select,+ Text,+ Tooltip,+ buttonStyle,+ rawTheme,+ theme,+} from "@webstudio-is/design-system";+import {+ HomePagePath,+ PageName,+ PagePath,+ ProjectNewRedirectPath,+ documentTypes,+ isLiteralExpression,+ type Page,+ type Pages,+} from "@webstudio-is/sdk";+import { HomeIcon, InfoCircleIcon } from "@webstudio-is/icons";+import {+ BindingControl,+ BindingPopover,+} from "~/builder/shared/binding-popover";+import { computeExpression } from "~/shared/data-variables";+import { $permissions } from "~/shared/nano-states";+import { $pageRootScope, isPathAvailable } from "../page-utils";+import { validatePathnamePattern } from "~/builder/shared/url-pattern";+import {+ LOOP_ERROR,+ wouldCreateLoop,+} from "~/shared/redirects/redirect-loop-detection";+import type { Errors, OnChange, Values } from "./shared";++// 2xx, 3xx, 4xx, 5xx+const statusRegex = /^[2345]\d\d$/;+const Status = z+ .number()+ .refine(+ (value) => statusRegex.test(String(value)),+ "Status code expects 2xx, 3xx, 4xx or 5xx"+ );++const GeneralValues = z.object({+ name: PageName,+ path: PagePath,+ status: Status.optional(),+ redirect: z.optional(ProjectNewRedirectPath.or(z.literal(""))),+ documentType: z.optional(z.enum(documentTypes)),+});++const HomePageGeneralValues = GeneralValues.extend({+ path: HomePagePath,+});++export const validateGeneralSection = ({+ pages,+ pageId,+ values,+ variableValues,+}: {+ pages: undefined | Pages;+ pageId: undefined | Page["id"];+ values: Values;+ variableValues: Map<string, unknown>;+}): Errors => {+ const computedValues = {+ name: values.name,+ path: values.path,+ status: computeExpression(values.status ?? `undefined`, variableValues),+ redirect: computeExpression(values.redirect, variableValues),+ documentType: values.documentType,+ };++ const Validator = values.isHomePage ? HomePageGeneralValues : GeneralValues;+ const parsedResult = Validator.safeParse(computedValues);+ const errors: Errors = {};+ if (parsedResult.success === false) {+ Object.assign(errors, parsedResult.error.formErrors.fieldErrors);+ }++ if (pages !== undefined && values.path !== undefined) {+ if (+ isPathAvailable({+ pages,+ path: values.path,+ parentFolderId: values.parentFolderId,+ pageId,+ }) === false+ ) {+ errors.path = errors.path ?? [];+ errors.path.push("All paths must be unique");+ }+ const messages = validatePathnamePattern(values.path);+ if (messages.length > 0) {+ errors.path = errors.path ?? [];+ errors.path.push(...messages);+ }+ }++ if (+ pages !== undefined &&+ values.path !== undefined &&+ computedValues.redirect &&+ typeof computedValues.redirect === "string" &&+ computedValues.redirect !== ""+ ) {+ const existingRedirects = pages.redirects ?? [];+ if (+ wouldCreateLoop(values.path, computedValues.redirect, existingRedirects)+ ) {+ errors.redirect = errors.redirect ?? [];+ errors.redirect.push(LOOP_ERROR);+ }+ }++ return errors;+};++const autoSelectHandler: FocusEventHandler<HTMLInputElement> = (event) =>+ event.target.select();++const PathField = ({+ errors,+ value,+ onChange,+}: {+ errors?: string[];+ value: string;+ onChange: (value: string) => void;+}) => {+ const { allowDynamicData } = useStore($permissions);+ const id = useId();+ return (+ <Grid gap={1}>+ <Flex align="center" gap={1}>+ <Label htmlFor={id}>Path</Label>+ {allowDynamicData === false && <ProBadge>PRO</ProBadge>}+ <Tooltip+ content={+ <>+ <Text>+ 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 whole remaining part at the end of the URL.+ </Text>+ {allowDynamicData === false && (+ <>+ <br />+ <Text>+ To make the path dynamic and use it with CMS, you can use+ parameters and other features. You can publish to staging+ for free; upgrade to Pro to publish to custom domains.+ </Text>+ <Link+ className={buttonStyle({ color: "gradient" })}+ css={{ marginTop: theme.spacing[5], width: "100%" }}+ color="contrast"+ underline="none"+ target="_blank"+ href="https://webstudio.is/pricing"+ >+ Upgrade+ </Link>+ </>+ )}+ </>+ }+ variant="wrapped"+ >+ <InfoCircleIcon+ color={rawTheme.colors.foregroundSubtle}+ tabIndex={-1}+ />+ </Tooltip>+ </Flex>+ <InputErrorsTooltip errors={errors}>+ <InputField+ color={errors && "error"}+ id={id}+ placeholder="/about"+ value={value}+ onChange={(event) => onChange(event.target.value)}+ />+ </InputErrorsTooltip>+ </Grid>+ );+};++const StatusField = ({+ errors,+ value = `undefined`,+ onChange,+}: {+ errors?: string[];+ value: undefined | string;+ onChange: (value: undefined | string) => void;+}) => {+ const id = useId();+ const { variableValues, scope, aliases } = useStore($pageRootScope);+ return (+ <Grid gap={1}>+ <Flex align="center" gap={1}>+ <Label htmlFor={id}>Status code </Label>+ <Tooltip+ content={+ <Text>+ Status code value can be a{" "}+ <Link+ color="inherit"+ target="_blank"+ href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status"+ >+ HTTP Status+ </Link>{" "}+ number or an expression that returns the status code dynamic+ response handling.+ </Text>+ }+ variant="wrapped"+ >+ <InfoCircleIcon+ color={rawTheme.colors.foregroundSubtle}+ tabIndex={-1}+ />+ </Tooltip>+ </Flex>+ <BindingControl>+ <BindingPopover+ scope={scope}+ aliases={aliases}+ variant={isLiteralExpression(value) ? "default" : "bound"}+ value={value}+ onChange={onChange}+ onRemove={(evaluatedValue) =>+ onChange(JSON.stringify(evaluatedValue ?? ""))+ }+ />+ <InputErrorsTooltip errors={errors}>+ <InputField+ inputMode="numeric"+ color={errors && "error"}+ id={id}+ placeholder="200"+ disabled={isLiteralExpression(value) === false}+ value={String(computeExpression(value, variableValues) ?? "")}+ onChange={(event) => {+ if (event.target.value === "") {+ onChange(undefined);+ } else {+ const number = Number(event.target.value);+ const status =+ Number.isNaN(number) || String(number) !== event.target.value+ ? event.target.value+ : number;+ onChange(JSON.stringify(status));+ }+ }}+ />+ </InputErrorsTooltip>+ </BindingControl>+ </Grid>+ );+};++const RedirectField = ({+ errors,+ value,+ onChange,+}: {+ errors?: string[];+ value: string;+ onChange: (value: string) => void;+}) => {+ const id = useId();+ const { allowDynamicData } = useStore($permissions);+ const { variableValues, scope, aliases } = useStore($pageRootScope);+ return (+ <Grid gap={1}>+ <Flex align="center" gap={1}>+ <Label htmlFor={id}>Redirect </Label>+ {allowDynamicData === false && <ProBadge>PRO</ProBadge>}+ <Tooltip+ content={+ <>+ <Text>+ Redirect value can be a path or an expression that returns a+ path for dynamic response handling.+ </Text>+ {allowDynamicData === false && (+ <>+ <br />+ <Text>+ Redirects are a Pro publishing feature. You can publish to+ staging for free; upgrade to Pro to publish to custom+ domains.+ </Text>+ <Link+ className={buttonStyle({ color: "gradient" })}+ css={{ marginTop: theme.spacing[5], width: "100%" }}+ color="contrast"+ underline="none"+ target="_blank"+ href="https://webstudio.is/pricing"+ >+ Upgrade+ </Link>+ </>+ )}+ </>+ }+ variant="wrapped"+ >+ <InfoCircleIcon+ color={rawTheme.colors.foregroundSubtle}+ tabIndex={-1}+ />+ </Tooltip>+ </Flex>++ <BindingControl>+ <BindingPopover+ scope={scope}+ aliases={aliases}+ variant={isLiteralExpression(value) ? "default" : "bound"}+ value={value}+ onChange={onChange}+ onRemove={(evaluatedValue) =>+ onChange(JSON.stringify(evaluatedValue ?? ""))+ }+ />+ <InputErrorsTooltip errors={errors}>+ <InputField+ color={errors && "error"}+ id={id}+ placeholder="/another-path"+ disabled={isLiteralExpression(value) === false}+ value={String(computeExpression(value, variableValues))}+ onChange={(event) => onChange(JSON.stringify(event.target.value))}+ />+ </InputErrorsTooltip>+ </BindingControl>+ </Grid>+ );+};++export const GeneralSection = ({+ autoSelect,+ errors,+ values,+ pages,+ onChange,+}: {+ autoSelect?: boolean;+ errors: Errors;+ values: Values;+ pages: Pages;+ onChange: OnChange;+}) => {+ const nameId = useId();+ const isHomePageId = useId();+ const documentTypeId = useId();+ return (+ <>+ <Grid gap={1}>+ <Label htmlFor={nameId}>Page name</Label>+ <InputErrorsTooltip errors={errors.name}>+ <InputField+ color={errors.name && "error"}+ id={nameId}+ autoFocus+ onFocus={autoSelect ? autoSelectHandler : undefined}+ name="name"+ placeholder="About"+ value={values.name}+ onChange={(event) => {+ onChange({ field: "name", value: event.target.value });+ }}+ />+ </InputErrorsTooltip>++ <Grid flow={"column"} gap={1} justify={"start"} align={"center"}>+ {values.isHomePage ? (+ <>+ <HomeIcon />+ <Text+ css={{+ overflowWrap: "anywhere",+ wordBreak: "break-all",+ my: 2,+ }}+ >+ “{values.name}” is the home page+ </Text>+ </>+ ) : values.parentFolderId !== pages.rootFolderId ? (+ <>+ <HomeIcon color={rawTheme.colors.foregroundSubtle} />+ <Text+ css={{+ overflowWrap: "anywhere",+ wordBreak: "break-all",+ my: 2,+ }}+ color="subtle"+ >+ Move this page to the “Root” folder to set it as your home page+ </Text>+ </>+ ) : values.documentType === "xml" ? (+ <>+ <HomeIcon color={rawTheme.colors.foregroundSubtle} />+ <Text+ css={{+ overflowWrap: "anywhere",+ wordBreak: "break-all",+ my: 2,+ }}+ color="subtle"+ >+ XML pages cannot be set as the home page+ </Text>+ </>+ ) : (+ <>+ <Checkbox+ id={isHomePageId}+ onCheckedChange={() => {+ onChange({ field: "path", value: "" });+ onChange({+ field: "isHomePage",+ value: !values.isHomePage,+ });+ }}+ />+ <Label+ css={{+ overflowWrap: "anywhere",+ wordBreak: "break-all",+ }}+ htmlFor={isHomePageId}+ >+ Make “{values.name}” the home page+ </Label>+ </>+ )}+ </Grid>+ </Grid>++ {values.isHomePage === false && (+ <PathField+ errors={errors.path}+ value={values.path}+ onChange={(value) => onChange({ field: "path", value })}+ />+ )}++ <StatusField+ errors={errors.status}+ value={values.status}+ onChange={(value) => onChange({ field: "status", value })}+ />+ <RedirectField+ errors={errors.redirect}+ value={values.redirect}+ onChange={(value) => onChange({ field: "redirect", value })}+ />++ <Grid gap={1}>+ <Label htmlFor={documentTypeId}>Document type</Label>+ <Select+ options={documentTypes}+ getValue={(docType: (typeof documentTypes)[number]) => docType}+ getLabel={(docType: (typeof documentTypes)[number]) =>+ docType.toLocaleUpperCase()+ }+ value={values.documentType}+ disabled={values.isHomePage}+ onChange={(value) => {+ onChange({+ field: "documentType",+ value,+ });+ }}+ />+ </Grid>+ </>+ );+};diff --git a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsxnew file mode 100644index 0000000000..d80d1c4e31--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx@@ -0,0 +1,120 @@+import { useId } from "react";+import { useStore } from "@nanostores/react";+import {+ Box,+ Button,+ Grid,+ InputField,+ Label,+ Switch,+ theme,+} from "@webstudio-is/design-system";+import { computeExpression } from "~/shared/data-variables";+import { ImageControl } from "~/shared/project-settings";+import { $assets } from "~/shared/sync/data-stores";+import { Card } from "../../marketplace/card";+import { ImageInfo } from "../image-info";+import type { OnChange, Values } from "./shared";++export const MarketplaceSection = ({+ values,+ onChange,+}: {+ values: Values;+ onChange: OnChange;+}) => {+ const excludeId = useId();+ const categoryId = useId();+ const categoryMeta = values.customMetas.find(+ ({ property }) => property === "ws:category"+ );+ // @todo remove after all stores are migrated+ const categoryFallback = String(+ computeExpression(categoryMeta?.content ?? `""`, new Map())+ );+ const category = values.marketplace.category ?? categoryFallback ?? "Pages";+ const assets = useStore($assets);+ const thumbnailAsset = assets.get(values.marketplace.thumbnailAssetId);+ const thumnailFallbackAsset = assets.get(values.socialImageAssetId);+ return (+ <Grid gap={2} css={{ padding: theme.panel.padding }}>+ <Grid+ flow="column"+ gap={1}+ justify="start"+ align="center"+ css={{ py: theme.spacing[2] }}+ >+ <Switch+ id={excludeId}+ checked={values.marketplace.include}+ onCheckedChange={(value) =>+ onChange({+ field: "marketplace",+ value: { ...values.marketplace, include: value },+ })+ }+ />+ <Label htmlFor={excludeId}>Include in the marketplace</Label>+ </Grid>+ <Grid gap={1}>+ <Label htmlFor={categoryId}>Category</Label>+ <InputField+ id={categoryId}+ name="marketplaceCategory"+ value={values.marketplace.category}+ onChange={(event) =>+ onChange({+ field: "marketplace",+ value: { ...values.marketplace, category: event.target.value },+ })+ }+ />+ </Grid>+ <Grid gap={1} flow="column">+ <ImageControl+ onAssetIdChange={(value) =>+ onChange({+ field: "marketplace",+ value: { ...values.marketplace, thumbnailAssetId: value },+ })+ }+ >+ <Button color="neutral" css={{ justifySelf: "start" }}>+ Choose thumbnail from assets+ </Button>+ </ImageControl>+ </Grid>+ {thumbnailAsset?.type === "image" && (+ <ImageInfo+ asset={thumbnailAsset}+ onDelete={() =>+ onChange({+ field: "marketplace",+ value: { ...values.marketplace, thumbnailAssetId: "" },+ })+ }+ />+ )}+ <Grid gap={1}>+ <Label>Marketplace preview</Label>+ <Box+ css={{+ padding: theme.spacing[5],+ borderRadius: theme.borderRadius[4],+ border: `1px solid ${theme.colors.borderMain}`,+ justifySelf: "start",+ }}+ >+ <Grid gap={1} css={{ width: theme.spacing[30] }}>+ {category && <Label text="title">{category}</Label>}+ <Card+ title={values.name}+ image={thumbnailAsset ?? thumnailFallbackAsset}+ />+ </Grid>+ </Box>+ </Grid>+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx b/apps/builder/app/builder/features/pages/page-settings/section-search.tsxnew file mode 100644index 0000000000..79bbf4cc1f--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx@@ -0,0 +1,304 @@+import { useId } from "react";+import * as bcp47 from "bcp-47";+import { z } from "zod";+import {+ Box,+ Checkbox,+ Grid,+ InputErrorsTooltip,+ InputField,+ Label,+ Text,+ TextArea,+ theme,+} from "@webstudio-is/design-system";+import { isLiteralExpression, PageTitle } from "@webstudio-is/sdk";+import {+ BindingControl,+ BindingPopover,+} from "~/builder/shared/binding-popover";+import { computeExpression } from "~/shared/data-variables";+import { useStore } from "@nanostores/react";+import { $assets, $pages } from "~/shared/sync/data-stores";+import { $pageRootScope } from "../page-utils";+import { SearchPreview } from "../search-preview";+import { usePageUrl, type Errors, type OnChange, type Values } from "./shared";++const EmptyString = z.string().refine((string) => string === "");++const Language = z+ .string()+ .refine(+ (value) => bcp47.parse(value).language !== null,+ "The language is invalid"+ );++const SearchValues = z.object({+ title: PageTitle,+ description: z.string().optional(),+ excludePageFromSearch: z.boolean().optional(),+ language: Language.or(EmptyString),+});++export const validateSearchSection = (+ values: Values,+ variableValues: Map<string, unknown>+): Errors => {+ const parsedResult = SearchValues.safeParse({+ title:+ computeExpression(values.title, variableValues) ??+ "exclude from validation",+ description: computeExpression(values.description, variableValues),+ excludePageFromSearch: computeExpression(+ values.excludePageFromSearch,+ variableValues+ ),+ language: computeExpression(values.language, variableValues),+ });+ return parsedResult.success ? {} : parsedResult.error.formErrors.fieldErrors;+};++const LanguageField = ({+ errors,+ value,+ onChange,+}: {+ errors?: string[];+ value: string;+ onChange: (value: string) => void;+}) => {+ const id = useId();+ const { variableValues, scope, aliases } = useStore($pageRootScope);+ return (+ <Grid gap={1}>+ <Label htmlFor={id}>Language</Label>+ <BindingControl>+ <BindingPopover+ scope={scope}+ aliases={aliases}+ variant={isLiteralExpression(value) ? "default" : "bound"}+ value={value}+ onChange={onChange}+ onRemove={(evaluatedValue) =>+ onChange(JSON.stringify(evaluatedValue ?? ""))+ }+ />+ <InputErrorsTooltip errors={errors}>+ <InputField+ color={errors && "error"}+ id={id}+ placeholder="en-US"+ disabled={isLiteralExpression(value) === false}+ value={String(computeExpression(value, variableValues))}+ onChange={(event) => onChange(JSON.stringify(event.target.value))}+ />+ </InputErrorsTooltip>+ </BindingControl>+ </Grid>+ );+};++export const SearchSection = ({+ values,+ errors,+ onChange,+}: {+ values: Values;+ errors: Errors;+ onChange: OnChange;+}) => {+ const titleId = useId();+ const descriptionId = useId();+ const excludePageFromSearchId = useId();+ const { variableValues, scope, aliases } = useStore($pageRootScope);+ const assets = useStore($assets);+ const pages = useStore($pages);+ const pageUrl = usePageUrl(values);+ const faviconAsset = assets.get(pages?.meta?.faviconAssetId ?? "");+ const faviconUrl = faviconAsset?.type === "image" ? faviconAsset.name : "";+ const title = String(computeExpression(values.title, variableValues));+ const description = String(+ computeExpression(values.description, variableValues)+ );+ const excludePageFromSearch = Boolean(+ computeExpression(values.excludePageFromSearch, variableValues)+ );+ return (+ <Grid gap={2}>+ <Grid gap={2}>+ <Text color="subtle">+ Optimize the way this page appears in search engine results pages.+ </Text>+ <Grid gap={1}>+ <Label>Search result preview</Label>+ <Box+ css={{+ padding: theme.spacing[5],+ background: theme.colors.white,+ borderRadius: theme.borderRadius[4],+ border: `1px solid ${theme.colors.borderMain}`,+ }}+ >+ <Box+ css={{+ transformOrigin: "top left",+ transform: "scale(0.667)",+ width: 600,+ height: 80,+ }}+ >+ <SearchPreview+ siteName={pages?.meta?.siteName ?? ""}+ faviconUrl={faviconUrl}+ pageUrl={pageUrl}+ titleLink={title}+ snippet={description}+ />+ </Box>+ </Box>+ </Grid>+ </Grid>++ <Grid gap={1}>+ <Label htmlFor={titleId}>Title</Label>+ <BindingControl>+ <BindingPopover+ scope={scope}+ aliases={aliases}+ variant={isLiteralExpression(values.title) ? "default" : "bound"}+ value={values.title}+ onChange={(value) => {+ onChange({+ field: "title",+ value,+ });+ }}+ onRemove={(evaluatedValue) => {+ onChange({+ field: "title",+ value: JSON.stringify(evaluatedValue ?? ""),+ });+ }}+ />+ <InputErrorsTooltip errors={errors.title}>+ <InputField+ color={errors.title && "error"}+ id={titleId}+ name="title"+ placeholder="My awesome project - About"+ disabled={isLiteralExpression(values.title) === false}+ value={title}+ onChange={(event) => {+ onChange({+ field: "title",+ value: JSON.stringify(event.target.value),+ });+ }}+ />+ </InputErrorsTooltip>+ </BindingControl>+ </Grid>++ <Grid gap={1}>+ <Label htmlFor={descriptionId}>Description</Label>+ <BindingControl>+ <BindingPopover+ scope={scope}+ aliases={aliases}+ variant={+ isLiteralExpression(values.description) ? "default" : "bound"+ }+ value={values.description}+ onChange={(value) => {+ onChange({+ field: "description",+ value,+ });+ }}+ onRemove={(evaluatedValue) => {+ onChange({+ field: "description",+ value: JSON.stringify(evaluatedValue ?? ""),+ });+ }}+ />+ <InputErrorsTooltip errors={errors.description}>+ <TextArea+ color={errors.description ? "error" : undefined}+ id={descriptionId}+ name="description"+ disabled={isLiteralExpression(values.description) === false}+ value={description}+ onChange={(value) => {+ onChange({+ field: "description",+ value: JSON.stringify(value),+ });+ }}+ autoGrow+ maxRows={10}+ />+ </InputErrorsTooltip>+ </BindingControl>+ <BindingControl>+ <Grid+ flow={"column"}+ gap={1}+ justify={"start"}+ align={"center"}+ css={{ py: theme.spacing[2] }}+ >+ <BindingPopover+ scope={scope}+ aliases={aliases}+ variant={+ isLiteralExpression(values.excludePageFromSearch)+ ? "default"+ : "bound"+ }+ value={values.excludePageFromSearch}+ onChange={(value) => {+ onChange({+ field: "excludePageFromSearch",+ value,+ });+ }}+ onRemove={(evaluatedValue) => {+ onChange({+ field: "excludePageFromSearch",+ value: JSON.stringify(evaluatedValue ?? ""),+ });+ }}+ />+ <Checkbox+ id={excludePageFromSearchId}+ disabled={+ isLiteralExpression(values.excludePageFromSearch) === false+ }+ checked={excludePageFromSearch}+ onCheckedChange={() => {+ const newValue = !excludePageFromSearch;+ onChange({+ field: "excludePageFromSearch",+ value: newValue.toString(),+ });+ }}+ />++ <InputErrorsTooltip errors={errors.excludePageFromSearch}>+ <Label htmlFor={excludePageFromSearchId}>+ Exclude this page from search results+ </Label>+ </InputErrorsTooltip>+ </Grid>+ </BindingControl>+ </Grid>++ <LanguageField+ errors={errors.language}+ value={values.language}+ onChange={(value) => onChange({ field: "language", value })}+ />+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsxnew file mode 100644index 0000000000..226a156315--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx@@ -0,0 +1,148 @@+import { useId } from "react";+import { useStore } from "@nanostores/react";+import { z } from "zod";+import {+ Button,+ Grid,+ InputErrorsTooltip,+ InputField,+ Text,+} from "@webstudio-is/design-system";+import {+ BindingControl,+ BindingPopover,+} from "~/builder/shared/binding-popover";+import { computeExpression } from "~/shared/data-variables";+import { ImageControl } from "~/shared/project-settings";+import { $assets } from "~/shared/sync/data-stores";+import { isLiteralExpression } from "@webstudio-is/sdk";+import { $pageRootScope } from "../page-utils";+import { ImageInfo } from "../image-info";+import { SocialPreview } from "../social-preview";+import { usePageUrl, type Errors, type OnChange, type Values } from "./shared";++const SocialImageValues = z.object({+ socialImageUrl: z.string().optional(),+});++export const validateSocialImageSection = (+ values: Values,+ variableValues: Map<string, unknown>+): Errors => {+ const parsedResult = SocialImageValues.safeParse({+ socialImageUrl: computeExpression(values.socialImageUrl, variableValues),+ });+ return parsedResult.success ? {} : parsedResult.error.formErrors.fieldErrors;+};++export const SocialImageSection = ({+ values,+ errors,+ onChange,+}: {+ values: Values;+ errors: Errors;+ onChange: OnChange;+}) => {+ const socialImageAssetButtonId = useId();+ const assets = useStore($assets);+ const socialImageAsset = assets.get(values.socialImageAssetId);+ const { variableValues, scope, aliases } = useStore($pageRootScope);+ const socialImageUrl = String(+ computeExpression(values.socialImageUrl, variableValues)+ );+ const pageUrl = usePageUrl(values);+ const title = String(computeExpression(values.title, variableValues));+ const description = String(+ computeExpression(values.description, variableValues)+ );+ return (+ <Grid gap={2}>+ <Text color="subtle">+ This image appears when you share a link to this page on social media+ sites. If no image is set here, the Social Image set in the project+ settings will be used. The optimal dimensions for the image are 1200x630+ px or larger with a 1.91:1 aspect ratio.+ </Text>+ <BindingControl>+ <BindingPopover+ scope={scope}+ aliases={aliases}+ variant={+ isLiteralExpression(values.socialImageUrl) ? "default" : "bound"+ }+ value={values.socialImageUrl}+ onChange={(value) => {+ onChange({+ field: "socialImageUrl",+ value,+ });+ }}+ onRemove={(evaluatedValue) => {+ onChange({+ field: "socialImageUrl",+ value: JSON.stringify(evaluatedValue ?? ""),+ });+ }}+ />+ <InputErrorsTooltip errors={errors.socialImageUrl}>+ <InputField+ placeholder="https://www.url.com"+ disabled={isLiteralExpression(values.socialImageUrl) === false}+ color={errors.socialImageUrl && "error"}+ value={socialImageUrl}+ onChange={(event) => {+ onChange({+ field: "socialImageUrl",+ value: JSON.stringify(event.target.value),+ });+ onChange({ field: "socialImageAssetId", value: "" });+ }}+ />+ </InputErrorsTooltip>+ </BindingControl>+ <Grid gap={1} flow={"column"}>+ <ImageControl+ onAssetIdChange={(socialImageAssetId) => {+ onChange({+ field: "socialImageAssetId",+ value: socialImageAssetId,+ });+ onChange({ field: "socialImageUrl", value: "" });+ }}+ >+ <Button+ id={socialImageAssetButtonId}+ css={{ justifySelf: "start" }}+ color="neutral"+ >+ Choose Image From Assets+ </Button>+ </ImageControl>+ </Grid>++ {socialImageAsset?.type === "image" && (+ <ImageInfo+ asset={socialImageAsset}+ onDelete={() => {+ onChange({+ field: "socialImageAssetId",+ value: "",+ });+ }}+ />+ )}+ <div />+ <SocialPreview+ ogImageUrl={+ socialImageAsset?.type === "image"+ ? socialImageAsset.name+ : socialImageUrl+ }+ ogUrl={pageUrl}+ ogTitle={title}+ ogDescription={description}+ />+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/pages/page-settings/shared.ts b/apps/builder/app/builder/features/pages/page-settings/shared.tsnew file mode 100644index 0000000000..9a80b8a0ad--- /dev/null+++ b/apps/builder/app/builder/features/pages/page-settings/shared.ts@@ -0,0 +1,77 @@+import { useStore } from "@nanostores/react";+import { getPagePath, type Page } from "@webstudio-is/sdk";+import {+ compilePathnamePattern,+ tokenizePathnamePattern,+} from "~/builder/shared/url-pattern";+import { $publishedOrigin } from "~/shared/nano-states";+import { $pages } from "~/shared/sync/data-stores";+import { $currentSystem } from "~/shared/system";++export type Values = {+ name: string;+ parentFolderId: string;+ path: string;+ isHomePage: boolean;+ title: string;+ description: string;+ excludePageFromSearch: string;+ language: string;+ socialImageUrl: string;+ socialImageAssetId: string;+ status: string | undefined;+ redirect: string;+ documentType: NonNullable<Page["meta"]["documentType"]>;+ auth: {+ login: string;+ password: string;+ };+ customMetas: { property: string; content: string }[];+ marketplace: {+ include: boolean;+ category: string;+ thumbnailAssetId: string;+ };+};++export type FieldName = keyof Values;++export type OnChange = (+ event: {+ [K in keyof Values]: {+ field: K;+ value: Values[K];+ };+ }[keyof Values]+) => void;++export type Errors = {+ [fieldName in Exclude<FieldName, "auth">]?: string[];+} & {+ auth?: {+ login?: string[];+ password?: string[];+ };+};++export const usePageUrl = (values: Values) => {+ const pages = useStore($pages);+ let path = "";+ if (pages !== undefined) {+ if (values.isHomePage) {+ path = "/";+ } else {+ const foldersPath = getPagePath(values.parentFolderId, pages);+ path = [foldersPath, values.path]+ .filter(Boolean)+ .join("/")+ .replace(/\/+/g, "/");+ }+ }++ const system = useStore($currentSystem);+ const publishedOrigin = useStore($publishedOrigin);+ const tokens = tokenizePathnamePattern(path);+ const compiledPath = compilePathnamePattern(tokens, system.params);+ return `${publishedOrigin}${compiledPath}`;+};diff --git a/apps/builder/app/builder/features/pages/pages.tsx b/apps/builder/app/builder/features/pages/pages.tsxindex 55f1e580de..9814d3bb60 100644--- a/apps/builder/app/builder/features/pages/pages.tsx+++ b/apps/builder/app/builder/features/pages/pages.tsx@@ -26,7 +26,7 @@ import {PageIcon,DynamicPageIcon,} from "@webstudio-is/icons";-import { NewPageSettings, PageSettings } from "./page-settings";+import { NewPageSettings, PageSettings } from "./page-settings/page-settings";import { PageContextMenu } from "./page-context-menu";import {DeletePageConfirmationDialog,@@ -427,7 +427,6 @@ const PageEditor = ({if (editingPageId === newPageId) {return (<NewPageSettings- onClose={onClose}onSuccess={(pageId) => {onClose();selectPage(pageId);diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsxindex eeb722f229..d10b305394 100644--- a/apps/builder/app/builder/features/publish/publish.tsx+++ b/apps/builder/app/builder/features/publish/publish.tsx@@ -8,7 +8,6 @@ import {startTransition,useRef,useId,- type ReactNode,} from "react";import { useStore } from "@nanostores/react";import {@@ -43,7 +42,6 @@ import {} from "@webstudio-is/design-system";import { validateProjectDomain, type Project } from "@webstudio-is/project";import { $selectedInstanceSelector } from "~/shared/nano-states";-import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils";import { $selectedPageId } from "~/shared/nano-states";import {$authTokenPermissions,@@ -72,11 +70,7 @@ import {import { AddDomain } from "./add-domain";import { humanizeString } from "~/shared/string-utils";import { trpcClient, nativeClient } from "~/shared/trpc/trpc-client";-import {- getAllPages,- isPathnamePattern,- type Templates,-} from "@webstudio-is/sdk";+import { type Templates } from "@webstudio-is/sdk";import { DomainCheckbox, domainToPublishName } from "./domain-checkbox";import { CopyToClipboard } from "~/shared/copy-to-clipboard";import { $openProjectSettings } from "~/shared/nano-states/project-settings";@@ -85,6 +79,10 @@ import { RelativeTime } from "~/builder/shared/relative-time";import cmsUpgradeBanner from "~/shared/cms-upgrade-banner.svg?url";import { $currentSystem } from "~/shared/system";import { getPublishUrl } from "./publish-url";+import {+ getRestrictedFeatures,+ type RestrictedFeature,+} from "./restricted-features";type ChangeProjectDomainProps = {project: Project;@@ -316,57 +314,8 @@ const ChangeProjectDomain = ({const $restrictedFeatures = computed([$pages, $dataSources, $instances, $permissions],- (pages, dataSources, instances, permissions) => {- const features = new Map<- string,- | undefined- | {- navigate?: { pageId: string; instanceSelector: string[] };- view?: "pageSettings";- info?: ReactNode;- }- >();- if (pages === undefined) {- return features;- }- // specified emails for default webhook form- if (- permissions.maxContactEmailsPerProject === 0 &&- (pages?.meta?.contactEmail ?? "").trim()- ) {- features.set("Custom contact email", undefined);- }- if (!permissions.allowDynamicData) {- // pages with dynamic paths- for (const page of getAllPages(pages)) {- const navigate = {- pageId: page.id,- instanceSelector: [page.rootInstanceId],- };- // allow catch all for 404 pages on free plan- if (isPathnamePattern(page.path) && page.path !== "/*") {- features.set("Dynamic path", { navigate, view: "pageSettings" });- }- if (page.meta.redirect && page.meta.redirect !== `""`) {- features.set("Redirect", { navigate, view: "pageSettings" });- }- }- // has resource variables- for (const dataSource of dataSources.values()) {- if (dataSource.type === "resource") {- const instanceId = dataSource.scopeInstanceId ?? "";- features.set("Resource variable", {- navigate: findPageAndSelectorByInstanceId(- pages,- instances,- instanceId- ),- });- }- }- }- return features;- }+ (pages, dataSources, instances, permissions) =>+ getRestrictedFeatures({ pages, dataSources, instances, permissions }));const usePublishCountdown = (isPublishing: boolean) => {@@ -408,15 +357,7 @@ const Publish = ({timesLeft: number;disabled: boolean;refresh: () => Promise<void>;- restrictedFeatures: Map<- string,- | undefined- | {- navigate?: { pageId: string; instanceSelector: string[] };- view?: "pageSettings";- info?: ReactNode;- }- >;+ restrictedFeatures: Map<string, RestrictedFeature>;}) => {const { maxDailyPublishesPerUser } = useStore($permissions);const { userPublishCount } = useUserPublishCount();diff --git a/apps/builder/app/builder/features/publish/restricted-features.test.ts b/apps/builder/app/builder/features/publish/restricted-features.test.tsnew file mode 100644index 0000000000..645aad2a76--- /dev/null+++ b/apps/builder/app/builder/features/publish/restricted-features.test.ts@@ -0,0 +1,160 @@+import { describe, expect, test } from "vitest";+import {+ ROOT_FOLDER_ID,+ type DataSource,+ type Folder,+ type Instance,+ type Page,+ type Pages,+} from "@webstudio-is/sdk";+import {+ getRestrictedFeatures,+ type RestrictedFeaturesPermissions,+} from "./restricted-features";++const createPage = (page: Partial<Page> & Pick<Page, "id">): Page => ({+ name: page.id,+ path: page.id === "home" ? "" : `/${page.id}`,+ title: `"${page.id}"`,+ meta: {},+ rootInstanceId: `${page.id}-root`,+ ...page,+});++const createFolder = (+ folder: Partial<Folder> & Pick<Folder, "id">+): Folder => ({+ name: folder.id,+ slug: folder.id,+ children: [],+ ...folder,+});++const homePage = createPage({ id: "home" });++const createPages = ({+ pages = [homePage],+ meta,+}: {+ pages?: Page[];+ meta?: Pages["meta"];+} = {}): Pages => ({+ homePageId: homePage.id,+ rootFolderId: ROOT_FOLDER_ID,+ pages: new Map(pages.map((page) => [page.id, page])),+ folders: new Map([+ [+ ROOT_FOLDER_ID,+ createFolder({+ id: ROOT_FOLDER_ID,+ name: "Root",+ slug: "",+ children: pages.map((page) => page.id),+ }),+ ],+ ]),+ meta,+});++const defaultPermissions: RestrictedFeaturesPermissions = {+ maxContactEmailsPerProject: 1,+ allowAuth: true,+ allowDynamicData: true,+};++const getFeatures = ({+ pages,+ permissions,+}: {+ pages: Pages | undefined;+ permissions: Partial<RestrictedFeaturesPermissions>;+}) =>+ getRestrictedFeatures({+ pages,+ dataSources: new Map<string, DataSource>(),+ instances: new Map<string, Instance>(),+ permissions: { ...defaultPermissions, ...permissions },+ });++describe("getRestrictedFeatures", () => {+ test("restricts project authentication when auth is not allowed", () => {+ const features = getFeatures({+ pages: createPages({+ meta: {+ auth: JSON.stringify({+ version: 1,+ routes: {+ "/private": {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ },+ }),+ },+ }),+ permissions: { allowAuth: false },+ });++ expect(features.has("Project auth")).toBe(true);+ });++ test("restricts page authentication when auth is not allowed", () => {+ const privatePage = createPage({+ id: "private",+ meta: {+ auth: {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ },+ });+ const features = getFeatures({+ pages: createPages({ pages: [homePage, privatePage] }),+ permissions: { allowAuth: false },+ });++ expect(features.get("Page auth")).toEqual({+ navigate: {+ pageId: privatePage.id,+ instanceSelector: [privatePage.rootInstanceId],+ },+ view: "pageSettings",+ });+ });++ test("allows project and page authentication when auth is allowed", () => {+ const privatePage = createPage({+ id: "private",+ meta: {+ auth: {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ },+ });+ const features = getFeatures({+ pages: createPages({+ pages: [homePage, privatePage],+ meta: {+ auth: JSON.stringify({+ version: 1,+ routes: {+ "/private": {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ },+ }),+ },+ }),+ permissions: { allowAuth: true },+ });++ expect(features.has("Project auth")).toBe(false);+ expect(features.has("Page auth")).toBe(false);+ });+});diff --git a/apps/builder/app/builder/features/publish/restricted-features.ts b/apps/builder/app/builder/features/publish/restricted-features.tsnew file mode 100644index 0000000000..516c35d9b5--- /dev/null+++ b/apps/builder/app/builder/features/publish/restricted-features.ts@@ -0,0 +1,89 @@+import type { ReactNode } from "react";+import {+ getAllPages,+ isPathnamePattern,+ type DataSource,+ type Instance,+ type Pages,+} from "@webstudio-is/sdk";+import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils";++export type RestrictedFeature =+ | undefined+ | {+ navigate?: { pageId: string; instanceSelector: string[] };+ view?: "pageSettings";+ info?: ReactNode;+ };++export type RestrictedFeaturesPermissions = {+ maxContactEmailsPerProject: number;+ allowAuth: boolean;+ allowDynamicData: boolean;+};++export const getRestrictedFeatures = ({+ pages,+ dataSources,+ instances,+ permissions,+}: {+ pages: Pages | undefined;+ dataSources: Map<string, DataSource>;+ instances: Map<string, Instance>;+ permissions: RestrictedFeaturesPermissions;+}) => {+ const features = new Map<string, RestrictedFeature>();+ if (pages === undefined) {+ return features;+ }+ if (+ permissions.maxContactEmailsPerProject === 0 &&+ (pages.meta?.contactEmail ?? "").trim()+ ) {+ features.set("Custom contact email", undefined);+ }+ if (permissions.allowAuth === false) {+ if ((pages.meta?.auth ?? "").trim()) {+ features.set("Project auth", undefined);+ }+ for (const page of getAllPages(pages)) {+ if (page.meta.auth !== undefined) {+ features.set("Page auth", {+ navigate: {+ pageId: page.id,+ instanceSelector: [page.rootInstanceId],+ },+ view: "pageSettings",+ });+ }+ }+ }+ if (permissions.allowDynamicData === false) {+ for (const page of getAllPages(pages)) {+ const navigate = {+ pageId: page.id,+ instanceSelector: [page.rootInstanceId],+ };+ if (isPathnamePattern(page.path) && page.path !== "/*") {+ features.set("Dynamic path", { navigate, view: "pageSettings" });+ }+ if (page.meta.redirect && page.meta.redirect !== `""`) {+ features.set("Redirect", { navigate, view: "pageSettings" });+ }+ }+ for (const dataSource of dataSources.values()) {+ if (dataSource.type === "resource") {+ const instanceId = dataSource.scopeInstanceId ?? "";+ features.set("Resource variable", {+ navigate: findPageAndSelectorByInstanceId(+ pages,+ instances,+ instanceId+ ),+ });+ }+ }+ }+ return features;+};diff --git a/apps/builder/app/builder/shared/assets/asset-upload.test.ts b/apps/builder/app/builder/shared/assets/asset-upload.test.tsindex 6d7a94f802..c02cf4bd58 100644--- a/apps/builder/app/builder/shared/assets/asset-upload.test.ts+++ b/apps/builder/app/builder/shared/assets/asset-upload.test.ts@@ -1,22 +1,12 @@import { describe, test, expect, vi, afterEach } from "vitest";+import { toast } from "@webstudio-is/design-system";import {acceptFileTypeSpecifier,validateFiles,acceptUploadType,} from "./asset-upload";-const mockToast = vi.hoisted(() => ({- error: vi.fn(),-}));--vi.mock("@webstudio-is/design-system", async (importOriginal) => {- const actual =- await importOriginal<typeof import("@webstudio-is/design-system")>();- return {- ...actual,- toast: mockToast,- };-});+const toastError = vi.spyOn(toast, "error").mockImplementation(() => "");describe("validateFiles", () => {afterEach(() => {@@ -36,7 +26,7 @@ describe("validateFiles", () => {expect(result).toHaveLength(2);expect(result).toContain(smallFile1);expect(result).toContain(smallFile2);- expect(mockToast.error).not.toHaveBeenCalled();+ expect(toastError).not.toHaveBeenCalled();});test("filters out files exceeding size limit and shows toast error", () => {@@ -55,7 +45,7 @@ describe("validateFiles", () => {expect(result).toHaveLength(1);expect(result).toContain(smallFile);- expect(mockToast.error).toHaveBeenCalledWith(+ expect(toastError).toHaveBeenCalledWith('Asset "large.jpg" cannot be bigger than 4.5MB');});@@ -78,11 +68,11 @@ describe("validateFiles", () => {const result = validateFiles([largeFile1, largeFile2]);expect(result).toHaveLength(0);- expect(mockToast.error).toHaveBeenCalledTimes(2);- expect(mockToast.error).toHaveBeenCalledWith(+ expect(toastError).toHaveBeenCalledTimes(2);+ expect(toastError).toHaveBeenCalledWith('Asset "large1.jpg" cannot be bigger than 4.5MB');- expect(mockToast.error).toHaveBeenCalledWith(+ expect(toastError).toHaveBeenCalledWith('Asset "large2.jpg" cannot be bigger than 4.5MB');});diff --git a/apps/builder/app/shared/nano-states/project-settings.ts b/apps/builder/app/shared/nano-states/project-settings.tsindex 629a9a8f77..0baad19f22 100644--- a/apps/builder/app/shared/nano-states/project-settings.ts+++ b/apps/builder/app/shared/nano-states/project-settings.ts@@ -2,6 +2,7 @@ import { atom } from "nanostores";export type SectionName =| "general"+ | "auth"| "redirects"| "publish"| "marketplace"diff --git a/apps/builder/app/shared/page-utils.ts b/apps/builder/app/shared/page-utils.tsindex 3f5d2ebf87..5cf72635b8 100644--- a/apps/builder/app/shared/page-utils.ts+++ b/apps/builder/app/shared/page-utils.ts@@ -181,6 +181,9 @@ export const insertPageCopyMutable = ({if (newPage.meta.redirect !== undefined) {newPage.meta.redirect = transformExpression(newPage.meta.redirect);}+ if (newPage.meta.auth !== undefined) {+ newPage.meta.auth = { ...newPage.meta.auth };+ }if (newPage.meta.custom) {newPage.meta.custom = newPage.meta.custom.map(({ property, content }) => ({property,diff --git a/apps/builder/app/shared/permissions.test.ts b/apps/builder/app/shared/permissions.test.tsindex 1e64296533..4b4d836ace 100644--- a/apps/builder/app/shared/permissions.test.ts+++ b/apps/builder/app/shared/permissions.test.ts@@ -6,6 +6,7 @@ const defaultPlanPermissions = {canDownloadAssets: false,canRestoreBackups: false,allowDynamicData: false,+ allowAuth: false,allowContentMode: false,allowStagingPublish: false,allowAdditionalPermissions: false,@@ -22,6 +23,7 @@ const proPlan = {canRestoreBackups: true,allowAdditionalPermissions: true,allowDynamicData: true,+ allowAuth: true,allowContentMode: true,allowStagingPublish: true,maxContactEmailsPerProject: 5,@@ -39,6 +41,7 @@ const freePlan = {canRestoreBackups: false,allowAdditionalPermissions: false,allowDynamicData: false,+ allowAuth: false,allowContentMode: false,allowStagingPublish: false,maxContactEmailsPerProject: 0,@@ -216,6 +219,7 @@ describe("getPermissions", () => {});expect(result).toMatchObject({allowDynamicData: true,+ allowAuth: true,allowContentMode: true,allowStagingPublish: true,allowAdditionalPermissions: true,@@ -236,6 +240,7 @@ describe("getPermissions", () => {});expect(result).toMatchObject({allowDynamicData: false,+ allowAuth: false,allowContentMode: false,allowStagingPublish: false,allowAdditionalPermissions: false,@@ -359,6 +364,7 @@ describe("getPermissions", () => {canDownloadAssets: false,canRestoreBackups: false,allowDynamicData: false,+ allowAuth: false,allowContentMode: false,allowStagingPublish: false,allowAdditionalPermissions: false,@@ -391,6 +397,7 @@ describe("getPermissions", () => {canDownloadAssets: true,canRestoreBackups: true,allowDynamicData: true,+ allowAuth: true,allowContentMode: true,allowStagingPublish: true,allowAdditionalPermissions: true,@@ -423,6 +430,7 @@ describe("getPermissions", () => {canDownloadAssets: true,canRestoreBackups: true,allowDynamicData: true,+ allowAuth: true,allowContentMode: true,allowStagingPublish: true,allowAdditionalPermissions: true,@@ -455,6 +463,7 @@ describe("getPermissions", () => {canDownloadAssets: false,canRestoreBackups: false,allowDynamicData: false,+ allowAuth: false,allowContentMode: false,allowStagingPublish: false,allowAdditionalPermissions: false,@@ -487,6 +496,7 @@ describe("getPermissions", () => {canDownloadAssets: true,canRestoreBackups: true,allowDynamicData: true,+ allowAuth: true,allowContentMode: true,allowStagingPublish: true,allowAdditionalPermissions: true,diff --git a/apps/builder/app/shared/permissions.ts b/apps/builder/app/shared/permissions.tsindex 8efcb91466..54171458c6 100644--- a/apps/builder/app/shared/permissions.ts+++ b/apps/builder/app/shared/permissions.ts@@ -62,6 +62,7 @@ export const getPermissions = ({canDownloadAssets: planFeatures.canDownloadAssets,canRestoreBackups: planFeatures.canRestoreBackups,allowDynamicData: planFeatures.allowDynamicData,+ allowAuth: planFeatures.allowAuth,allowContentMode: isSharedProject || planFeatures.allowContentMode,allowStagingPublish: planFeatures.allowStagingPublish,allowAdditionalPermissions: planFeatures.allowAdditionalPermissions,diff --git a/apps/builder/app/shared/project-settings/project-settings.tsx b/apps/builder/app/shared/project-settings/project-settings.tsxindex 8b3f1b5cbb..d2526ac8d5 100644--- a/apps/builder/app/shared/project-settings/project-settings.tsx+++ b/apps/builder/app/shared/project-settings/project-settings.tsx@@ -21,6 +21,7 @@ import {import { $isDesignMode } from "~/shared/nano-states";import { leftPanelWidth, rightPanelWidth } from "./utils";import { SectionGeneral } from "./section-general";+import { SectionAuth } from "./section-auth";import { SectionRedirects } from "./section-redirects";import { SectionPublish } from "./section-publish";import { SectionMarketplace } from "./section-marketplace";@@ -36,8 +37,13 @@ const sections = new Map<["publish", SectionPublish],["marketplace", SectionMarketplace],["backups", SectionBackups],+ ["auth", SectionAuth],] as const);+const sectionLabels = new Map<SectionName, string>([+ ["auth", "Authentication"],+]);+export const ProjectSettingsDialog = ({currentSection,onSectionChange,@@ -109,7 +115,7 @@ export const ProjectSettingsDialog = ({align="center"><Text variant="labels" truncate>- {titleCase(name)}+ {sectionLabels.get(name) ?? titleCase(name)}</Text></Flex></ListItem>diff --git a/apps/builder/app/shared/project-settings/section-auth.test.ts b/apps/builder/app/shared/project-settings/section-auth.test.tsnew file mode 100644index 0000000000..59a28bb98b--- /dev/null+++ b/apps/builder/app/shared/project-settings/section-auth.test.ts@@ -0,0 +1,52 @@+import { describe, expect, test } from "vitest";++const [{ createBasicAuthRoute }, { __testing__ }] = await Promise.all([+ import("@webstudio-is/wsauth"),+ import("./section-auth"),+]);++const { parseAuthRoutes, validateRoute } = __testing__;++describe("project settings authentication", () => {+ test("parses stored auth config into editable routes", () => {+ expect(+ parseAuthRoutes(+ JSON.stringify({+ version: 1,+ routes: {+ "/private": {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ },+ })+ ).routes+ ).toEqual([+ createBasicAuthRoute({+ route: "/private",+ login: "admin",+ password: "secret",+ }),+ ]);+ });++ test("validates route input", () => {+ const authRoutes = [+ createBasicAuthRoute({+ route: "/private",+ login: "admin",+ password: "secret",+ }),+ ];++ expect(validateRoute("", authRoutes)).toEqual(["Route is required"]);+ expect(validateRoute("private", authRoutes)).toEqual([+ 'Route must start with "/"',+ ]);+ expect(validateRoute("/private", authRoutes)).toEqual([+ "This route already requires authentication",+ ]);+ expect(validateRoute("/docs/*", authRoutes)).toEqual([]);+ });+});diff --git a/apps/builder/app/shared/project-settings/section-auth.tsx b/apps/builder/app/shared/project-settings/section-auth.tsxnew file mode 100644index 0000000000..dd35eb0c0e--- /dev/null+++ b/apps/builder/app/shared/project-settings/section-auth.tsx@@ -0,0 +1,398 @@+import { useEffect, useMemo, useRef, useState } from "react";+import {+ Button,+ Combobox,+ Flex,+ Grid,+ InputErrorsTooltip,+ InputField,+ Link,+ List,+ ListItem,+ ProBadge,+ rawTheme,+ ScrollArea,+ SearchField,+ SmallIconButton,+ Text,+ theme,+ Tooltip,+ buttonStyle,+} from "@webstudio-is/design-system";+import { InfoCircleIcon, TrashIcon } from "@webstudio-is/icons";+import { useStore } from "@nanostores/react";+import {+ createBasicAuthRoute,+ parseWsAuth,+ serializeWsAuth,+ validateBasicAuth,+ type WsAuthRoute,+} from "@webstudio-is/wsauth";+import { $permissions } from "~/shared/nano-states";+import { $pages } from "~/shared/sync/data-stores";+import { serverSyncStore } from "~/shared/sync/sync-stores";+import { getExistingRoutePaths, sectionSpacing } from "./utils";++const parseAuthRoutes = (auth: string | undefined) => {+ return parseWsAuth(auth ?? "");+};++const validateRouteSyntax = (route: string) => {+ const result = parseWsAuth(+ JSON.stringify({+ version: 1,+ routes: {+ [route]: {+ method: "basic",+ login: "login",+ password: "password",+ },+ },+ })+ );+ return result.errors.find((error) =>+ error.path.startsWith(`routes.${JSON.stringify(route)}`)+ )?.message;+};++const saveAuthRoutes = (authRoutes: WsAuthRoute[]) => {+ serverSyncStore.createTransaction([$pages], (pages) => {+ if (pages === undefined) {+ return;+ }+ if (pages.meta === undefined) {+ pages.meta = {};+ }+ pages.meta.auth =+ authRoutes.length === 0 ? undefined : serializeWsAuth(authRoutes);+ });+};++const validateRoute = (route: string, authRoutes: WsAuthRoute[]) => {+ const errors: string[] = [];+ if (route === "") {+ errors.push("Route is required");+ return errors;+ }+ const routeError = validateRouteSyntax(route);+ if (routeError !== undefined) {+ errors.push(routeError);+ }+ if (authRoutes.some((authRoute) => authRoute.route === route)) {+ errors.push("This route already requires authentication");+ }+ return errors;+};++export const SectionAuth = () => {+ const { allowAuth } = useStore($permissions);+ const pages = useStore($pages);+ const routeRef = useRef<HTMLInputElement>(null);+ const [authRoutes, setAuthRoutes] = useState(() => {+ return parseAuthRoutes($pages.get()?.meta?.auth).routes;+ });+ const [route, setRoute] = useState("");+ const [login, setLogin] = useState("");+ const [password, setPassword] = useState("");+ const [routeErrors, setRouteErrors] = useState<string[]>([]);+ const [loginErrors, setLoginErrors] = useState<string[]>([]);+ const [passwordErrors, setPasswordErrors] = useState<string[]>([]);+ const [searchQuery, setSearchQuery] = useState("");++ const authContent = pages?.meta?.auth;+ const parseResult = useMemo(() => {+ return parseAuthRoutes(authContent);+ }, [authContent]);+ const parseErrors = parseResult.errors;++ useEffect(() => {+ setAuthRoutes(parseResult.routes);+ }, [parseResult.routes]);++ const existingPaths = getExistingRoutePaths(pages);+ const routeSuggestions = ["/", ...Array.from(existingPaths).sort()];+ const filteredAuthRoutes = searchQuery+ ? authRoutes.filter((authRoute) => {+ const query = searchQuery.toLowerCase();+ return (+ authRoute.route.toLowerCase().includes(query) ||+ authRoute.auth.login.toLowerCase().includes(query)+ );+ })+ : authRoutes;++ const handleRouteChange = (value: string) => {+ setRoute(value);+ setRouteErrors(validateRoute(value.trim(), authRoutes));+ };++ const handleSave = (nextAuthRoutes: WsAuthRoute[]) => {+ setAuthRoutes(nextAuthRoutes);+ saveAuthRoutes(nextAuthRoutes);+ };++ const handleAddAuthRoute = () => {+ const nextRoute = route.trim();+ const nextRouteErrors = validateRoute(nextRoute, authRoutes);+ const basicAuthValidation = validateBasicAuth({+ login,+ password,+ });+ const nextLoginErrors = basicAuthValidation.errors?.login ?? [];+ const nextPasswordErrors = basicAuthValidation.errors?.password ?? [];++ setRouteErrors(nextRouteErrors);+ setLoginErrors(nextLoginErrors);+ setPasswordErrors(nextPasswordErrors);++ if (+ nextRouteErrors.length > 0 ||+ nextLoginErrors.length > 0 ||+ nextPasswordErrors.length > 0+ ) {+ return;+ }++ handleSave([+ createBasicAuthRoute({+ route: nextRoute,+ login,+ password,+ }),+ ...authRoutes,+ ]);+ setRoute("");+ setLogin("");+ setPassword("");+ routeRef.current?.focus();+ };++ const handleDeleteAuthRoute = (index: number) => {+ const nextAuthRoutes = [...authRoutes];+ nextAuthRoutes.splice(index, 1);+ handleSave(nextAuthRoutes);+ };++ const handleReset = () => {+ setRouteErrors([]);+ setLoginErrors([]);+ setPasswordErrors([]);+ handleSave([]);+ };++ return (+ <Grid gap={3} css={sectionSpacing}>+ <Flex align="center" gap={1}>+ <Text variant="titles">Authentication</Text>+ {allowAuth === false && <ProBadge>PRO</ProBadge>}+ <Tooltip+ content={+ <>+ <Text>+ Authentication asks visitors for HTTP Basic Auth credentials+ before protected pages load on custom domains.+ </Text>+ <br />+ <Text>+ Routes use the same syntax as page paths, including :params and+ * wildcards.+ </Text>+ {allowAuth === false && (+ <>+ <br />+ <Text>+ Authentication is a Pro feature. You can publish to staging+ for free; upgrade to Pro to publish to custom domains.+ </Text>+ <Link+ className={buttonStyle({ color: "gradient" })}+ css={{ marginTop: theme.spacing[5], width: "100%" }}+ color="contrast"+ underline="none"+ target="_blank"+ href="https://webstudio.is/pricing"+ >+ Upgrade+ </Link>+ </>+ )}+ </>+ }+ variant="wrapped"+ >+ <InfoCircleIcon+ color={rawTheme.colors.foregroundSubtle}+ tabIndex={-1}+ />+ </Tooltip>+ </Flex>++ {parseErrors.length > 0 && (+ <Grid gap={2}>+ <Grid gap={1}>+ {parseErrors.map((error) => (+ <Text key={`${error.path}:${error.message}`} color="destructive">+ {error.path}: {error.message}+ </Text>+ ))}+ </Grid>+ <Flex>+ <Button color="destructive" onClick={handleReset}>+ Reset authentication+ </Button>+ </Flex>+ </Grid>+ )}++ <Flex gap="2" justify="between">+ <SearchField+ placeholder="Search"+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.target.value)}+ onAbort={() => setSearchQuery("")}+ disabled={authRoutes.length === 0}+ />+ <Button+ color="ghost"+ prefix={<TrashIcon />}+ disabled={authRoutes.length === 0}+ onClick={handleReset}+ >+ Delete all+ </Button>+ </Flex>++ <Flex gap="2" align="center">+ <InputErrorsTooltip+ errors={routeErrors.length > 0 ? routeErrors : undefined}+ side="top"+ >+ <Combobox<string>+ inputRef={routeRef}+ autoFocus+ placeholder="/private or /docs/*"+ value={route}+ color={routeErrors.length === 0 ? undefined : "error"}+ getItems={() => routeSuggestions}+ itemToString={(item) => item ?? ""}+ onItemSelect={(value) => handleRouteChange(value ?? "")}+ onChange={(value) => {+ if (value !== undefined) {+ handleRouteChange(value);+ }+ }}+ />+ </InputErrorsTooltip>++ <InputErrorsTooltip+ errors={loginErrors.length > 0 ? loginErrors : undefined}+ side="top"+ >+ <InputField+ placeholder="Login"+ value={login}+ color={loginErrors.length === 0 ? undefined : "error"}+ onChange={(event) => {+ setLogin(event.target.value);+ setLoginErrors([]);+ }}+ />+ </InputErrorsTooltip>++ <InputErrorsTooltip+ errors={passwordErrors.length > 0 ? passwordErrors : undefined}+ side="top"+ >+ <InputField+ placeholder="Password"+ type="password"+ value={password}+ color={passwordErrors.length === 0 ? undefined : "error"}+ onChange={(event) => {+ setPassword(event.target.value);+ setPasswordErrors([]);+ }}+ />+ </InputErrorsTooltip>++ <Button+ disabled={+ routeErrors.length > 0 ||+ loginErrors.length > 0 ||+ passwordErrors.length > 0+ }+ onClick={handleAddAuthRoute}+ css={{ flexShrink: 0 }}+ >+ Add+ </Button>+ </Flex>++ {authRoutes.length > 0 ? (+ <ScrollArea>+ <Grid>+ <List asChild>+ <Flex direction="column" gap="1" align="stretch">+ {filteredAuthRoutes.map((authRoute) => {+ const index = authRoutes.indexOf(authRoute);+ return (+ <ListItem asChild key={authRoute.route}>+ <Grid+ align="center"+ gap="2"+ css={{+ p: theme.spacing[3],+ overflow: "hidden",+ gridTemplateColumns: "1fr 1fr",+ position: "relative",+ "& > button": {+ opacity: 0,+ position: "absolute",+ right: 0,+ top: 0,+ bottom: 0,+ height: "auto",+ borderRadius: 0,+ background: theme.colors.backgroundPanel,+ },+ "&:hover > button, &:focus-within > button": {+ opacity: 1,+ },+ }}+ >+ <Tooltip content={authRoute.route}>+ <Text+ truncate+ css={{+ wordBreak: "break-all",+ }}+ >+ {authRoute.route}+ </Text>+ </Tooltip>+ <Tooltip content={authRoute.auth.login}>+ <Text truncate>{authRoute.auth.login}</Text>+ </Tooltip>+ <SmallIconButton+ variant="destructive"+ icon={<TrashIcon />}+ aria-label={`Delete authentication for ${authRoute.route}`}+ onClick={() => handleDeleteAuthRoute(index)}+ />+ </Grid>+ </ListItem>+ );+ })}+ </Flex>+ </List>+ </Grid>+ </ScrollArea>+ ) : null}+ </Grid>+ );+};++export const __testing__ = {+ parseAuthRoutes,+ validateRoute,+};diff --git a/apps/builder/app/shared/sync/project-queue.test.ts b/apps/builder/app/shared/sync/project-queue.test.tsindex c69b762560..2339b58711 100644--- a/apps/builder/app/shared/sync/project-queue.test.ts+++ b/apps/builder/app/shared/sync/project-queue.test.ts@@ -1,7 +1,15 @@/*** @vitest-environment jsdom*/-import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";+import {+ describe,+ test,+ expect,+ vi,+ beforeEach,+ afterEach,+ type MockInstance,+} from "vitest";import type { Backoff } from "@webstudio-is/sync-client";// Module mocks@@ -9,13 +17,11 @@ import type { Backoff } from "@webstudio-is/sync-client";const {mockBuildPatch,mockCreateNativeClient,- mockToastError,mockCreateBackoff,mockLoadBuilderData,} = vi.hoisted(() => ({mockBuildPatch: vi.fn(),mockCreateNativeClient: vi.fn(),- mockToastError: vi.fn(),mockCreateBackoff: vi.fn(),mockLoadBuilderData: vi.fn(),}));@@ -25,10 +31,6 @@ vi.mock("~/shared/trpc/trpc-client", () => ({nativeClient: { build: { patch: { mutate: mockBuildPatch } } },}));-vi.mock("@webstudio-is/design-system", () => ({- toast: { error: mockToastError },-}));-vi.mock("~/env/env.static", () => ({publicStaticEnv: { VERSION: "test-version" },}));@@ -46,6 +48,7 @@ vi.mock("~/shared/builder-data", () => ({import type { Change } from "immerhin";import { $hasUnsavedSyncChanges, $syncStatus } from "@webstudio-is/sync-client";+import { toast } from "@webstudio-is/design-system";import {$lastTransactionId,commandQueue,@@ -59,6 +62,7 @@ import {} from "./project-queue";const { retry, pollCommands, transactionCallbacks } = __testing__;+let mockToastError: MockInstance<typeof toast.error>;// Constants (duplicated to avoid exporting them just for tests)@@ -112,7 +116,7 @@ describe("project-queue", () => {build: { patch: { mutate: mockBuildPatch } },});mockBuildPatch.mockResolvedValue({ status: "ok" });- mockToastError.mockClear();+ mockToastError = vi.spyOn(toast, "error").mockImplementation(() => "");mockLoadBuilderData.mockResolvedValue({});});diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 28bccb86cf..b970e05323 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -125,7 +125,8 @@"valid-filename": "^4.0.0","warn-once": "^0.1.1","zod": "^3.24.2",- "zod-validation-error": "^3.4.0"+ "zod-validation-error": "^3.4.0",+ "@webstudio-is/wsauth": "workspace:*"},"devDependencies": {"@remix-run/dev": "^2.16.5",diff --git a/fixtures/react-router-cloudflare/.template/package.json b/fixtures/react-router-cloudflare/.template/package.jsonindex b21dce86c9..8b6d3adc73 100644--- a/fixtures/react-router-cloudflare/.template/package.json+++ b/fixtures/react-router-cloudflare/.template/package.json@@ -7,6 +7,7 @@"@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/sdk-components-react-radix": "workspace:*","@webstudio-is/sdk-components-react-router": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*","webstudio": "workspace:*"}}diff --git a/fixtures/react-router-cloudflare/.webstudio/auth.json b/fixtures/react-router-cloudflare/.webstudio/auth.jsonnew file mode 100644index 0000000000..6672d64b72--- /dev/null+++ b/fixtures/react-router-cloudflare/.webstudio/auth.json@@ -0,0 +1,4 @@+{+ "version": 1,+ "routes": {}+}diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.wsauth.server.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.wsauth.server.tsnew file mode 100644index 0000000000..5b5c11d290--- /dev/null+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.wsauth.server.ts@@ -0,0 +1,3 @@+import type { WsAuthRoute } from "@webstudio-is/wsauth";++export const authRoutes: WsAuthRoute[] = [];diff --git a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.tsxindex 601392f9bb..879db5f27a 100644--- a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.tsx@@ -8,6 +8,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2025-01-04T11:01:50.091Z";export const siteName = "";diff --git a/fixtures/react-router-cloudflare/app/__generated__/_index.tsx b/fixtures/react-router-cloudflare/app/__generated__/_index.tsxindex 240d73c36a..7e9af1e569 100644--- a/fixtures/react-router-cloudflare/app/__generated__/_index.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.tsx@@ -15,6 +15,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2025-01-04T11:01:50.091Z";export const siteName = "";diff --git a/fixtures/react-router-cloudflare/app/root.tsx b/fixtures/react-router-cloudflare/app/root.tsxindex bfd174e842..85f70e95ed 100644--- a/fixtures/react-router-cloudflare/app/root.tsx+++ b/fixtures/react-router-cloudflare/app/root.tsx@@ -1,10 +1,24 @@/* eslint-disable @typescript-eslint/ban-ts-comment */-import { Links, Meta, Outlet, useMatches } from "react-router";+import {+ type HeadersFunction,+ Links,+ Meta,+ Outlet,+ useMatches,+} from "react-router";// @todo think about how to make __generated__ typeable// @ts-ignoreimport { CustomCode, projectId, lastPublished } from "./__generated__/_index";+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }++ return {};+};+const Root = () => {// Get language from matchesconst matches = useMatches();diff --git a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsxindex b090c5c4f0..5eaf5d45f9 100644--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsxindex 2aed2df25e..c2af338d90 100644--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/react-router-cloudflare/package.json b/fixtures/react-router-cloudflare/package.jsonindex e2f139f22c..eb18131b45 100644--- a/fixtures/react-router-cloudflare/package.json+++ b/fixtures/react-router-cloudflare/package.json@@ -29,7 +29,8 @@"react-router": "^7.5.3","vite": "^6.3.4","webstudio": "workspace:*",- "wrangler": "^4.14.1"+ "wrangler": "^4.14.1",+ "@webstudio-is/wsauth": "workspace:*"},"type": "module","private": true,diff --git a/fixtures/react-router-docker/.template/package.json b/fixtures/react-router-docker/.template/package.jsonindex b21dce86c9..8b6d3adc73 100644--- a/fixtures/react-router-docker/.template/package.json+++ b/fixtures/react-router-docker/.template/package.json@@ -7,6 +7,7 @@"@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/sdk-components-react-radix": "workspace:*","@webstudio-is/sdk-components-react-router": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*","webstudio": "workspace:*"}}diff --git a/fixtures/react-router-docker/.webstudio/auth.json b/fixtures/react-router-docker/.webstudio/auth.jsonnew file mode 100644index 0000000000..6672d64b72--- /dev/null+++ b/fixtures/react-router-docker/.webstudio/auth.json@@ -0,0 +1,4 @@+{+ "version": 1,+ "routes": {}+}diff --git a/fixtures/react-router-docker/app/__generated__/$resources.wsauth.server.ts b/fixtures/react-router-docker/app/__generated__/$resources.wsauth.server.tsnew file mode 100644index 0000000000..5b5c11d290--- /dev/null+++ b/fixtures/react-router-docker/app/__generated__/$resources.wsauth.server.ts@@ -0,0 +1,3 @@+import type { WsAuthRoute } from "@webstudio-is/wsauth";++export const authRoutes: WsAuthRoute[] = [];diff --git a/fixtures/react-router-docker/app/__generated__/[another-page]._index.tsx b/fixtures/react-router-docker/app/__generated__/[another-page]._index.tsxindex 601392f9bb..879db5f27a 100644--- a/fixtures/react-router-docker/app/__generated__/[another-page]._index.tsx+++ b/fixtures/react-router-docker/app/__generated__/[another-page]._index.tsx@@ -8,6 +8,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2025-01-04T11:01:50.091Z";export const siteName = "";diff --git a/fixtures/react-router-docker/app/__generated__/_index.tsx b/fixtures/react-router-docker/app/__generated__/_index.tsxindex 240d73c36a..7e9af1e569 100644--- a/fixtures/react-router-docker/app/__generated__/_index.tsx+++ b/fixtures/react-router-docker/app/__generated__/_index.tsx@@ -15,6 +15,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2025-01-04T11:01:50.091Z";export const siteName = "";diff --git a/fixtures/react-router-docker/app/root.tsx b/fixtures/react-router-docker/app/root.tsxindex bfd174e842..85f70e95ed 100644--- a/fixtures/react-router-docker/app/root.tsx+++ b/fixtures/react-router-docker/app/root.tsx@@ -1,10 +1,24 @@/* eslint-disable @typescript-eslint/ban-ts-comment */-import { Links, Meta, Outlet, useMatches } from "react-router";+import {+ type HeadersFunction,+ Links,+ Meta,+ Outlet,+ useMatches,+} from "react-router";// @todo think about how to make __generated__ typeable// @ts-ignoreimport { CustomCode, projectId, lastPublished } from "./__generated__/_index";+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }++ return {};+};+const Root = () => {// Get language from matchesconst matches = useMatches();diff --git a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx b/fixtures/react-router-docker/app/routes/[another-page]._index.tsxindex b090c5c4f0..5eaf5d45f9 100644--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsxindex 2aed2df25e..c2af338d90 100644--- a/fixtures/react-router-docker/app/routes/_index.tsx+++ b/fixtures/react-router-docker/app/routes/_index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/react-router-docker/package.json b/fixtures/react-router-docker/package.jsonindex 8c68e53d1c..7b21fcbd74 100644--- a/fixtures/react-router-docker/package.json+++ b/fixtures/react-router-docker/package.json@@ -28,7 +28,8 @@"react-dom": "18.3.0-canary-14898b6a9-20240318","react-router": "^7.5.3","vite": "^6.3.4",- "webstudio": "workspace:*"+ "webstudio": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*"},"private": true,"sideEffects": false,diff --git a/fixtures/react-router-netlify/.template/package.json b/fixtures/react-router-netlify/.template/package.jsonindex b21dce86c9..8b6d3adc73 100644--- a/fixtures/react-router-netlify/.template/package.json+++ b/fixtures/react-router-netlify/.template/package.json@@ -7,6 +7,7 @@"@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/sdk-components-react-radix": "workspace:*","@webstudio-is/sdk-components-react-router": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*","webstudio": "workspace:*"}}diff --git a/fixtures/react-router-netlify/.webstudio/auth.json b/fixtures/react-router-netlify/.webstudio/auth.jsonnew file mode 100644index 0000000000..6672d64b72--- /dev/null+++ b/fixtures/react-router-netlify/.webstudio/auth.json@@ -0,0 +1,4 @@+{+ "version": 1,+ "routes": {}+}diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.wsauth.server.ts b/fixtures/react-router-netlify/app/__generated__/$resources.wsauth.server.tsnew file mode 100644index 0000000000..5b5c11d290--- /dev/null+++ b/fixtures/react-router-netlify/app/__generated__/$resources.wsauth.server.ts@@ -0,0 +1,3 @@+import type { WsAuthRoute } from "@webstudio-is/wsauth";++export const authRoutes: WsAuthRoute[] = [];diff --git a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.tsx b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.tsxindex 601392f9bb..879db5f27a 100644--- a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.tsx+++ b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.tsx@@ -8,6 +8,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2025-01-04T11:01:50.091Z";export const siteName = "";diff --git a/fixtures/react-router-netlify/app/__generated__/_index.tsx b/fixtures/react-router-netlify/app/__generated__/_index.tsxindex 240d73c36a..7e9af1e569 100644--- a/fixtures/react-router-netlify/app/__generated__/_index.tsx+++ b/fixtures/react-router-netlify/app/__generated__/_index.tsx@@ -15,6 +15,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2025-01-04T11:01:50.091Z";export const siteName = "";diff --git a/fixtures/react-router-netlify/app/root.tsx b/fixtures/react-router-netlify/app/root.tsxindex bfd174e842..85f70e95ed 100644--- a/fixtures/react-router-netlify/app/root.tsx+++ b/fixtures/react-router-netlify/app/root.tsx@@ -1,10 +1,24 @@/* eslint-disable @typescript-eslint/ban-ts-comment */-import { Links, Meta, Outlet, useMatches } from "react-router";+import {+ type HeadersFunction,+ Links,+ Meta,+ Outlet,+ useMatches,+} from "react-router";// @todo think about how to make __generated__ typeable// @ts-ignoreimport { CustomCode, projectId, lastPublished } from "./__generated__/_index";+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }++ return {};+};+const Root = () => {// Get language from matchesconst matches = useMatches();diff --git a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsxindex b090c5c4f0..5eaf5d45f9 100644--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsxindex 2aed2df25e..c2af338d90 100644--- a/fixtures/react-router-netlify/app/routes/_index.tsx+++ b/fixtures/react-router-netlify/app/routes/_index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/react-router-netlify/package.json b/fixtures/react-router-netlify/package.jsonindex cd6a49ab1b..955fb7ad1c 100644--- a/fixtures/react-router-netlify/package.json+++ b/fixtures/react-router-netlify/package.json@@ -28,7 +28,8 @@"react-dom": "18.3.0-canary-14898b6a9-20240318","react-router": "^7.5.3","vite": "^6.3.4",- "webstudio": "workspace:*"+ "webstudio": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*"},"type": "module","private": true,diff --git a/fixtures/react-router-vercel/.template/package.json b/fixtures/react-router-vercel/.template/package.jsonindex b21dce86c9..8b6d3adc73 100644--- a/fixtures/react-router-vercel/.template/package.json+++ b/fixtures/react-router-vercel/.template/package.json@@ -7,6 +7,7 @@"@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/sdk-components-react-radix": "workspace:*","@webstudio-is/sdk-components-react-router": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*","webstudio": "workspace:*"}}diff --git a/fixtures/react-router-vercel/.webstudio/auth.json b/fixtures/react-router-vercel/.webstudio/auth.jsonnew file mode 100644index 0000000000..6672d64b72--- /dev/null+++ b/fixtures/react-router-vercel/.webstudio/auth.json@@ -0,0 +1,4 @@+{+ "version": 1,+ "routes": {}+}diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.wsauth.server.ts b/fixtures/react-router-vercel/app/__generated__/$resources.wsauth.server.tsnew file mode 100644index 0000000000..5b5c11d290--- /dev/null+++ b/fixtures/react-router-vercel/app/__generated__/$resources.wsauth.server.ts@@ -0,0 +1,3 @@+import type { WsAuthRoute } from "@webstudio-is/wsauth";++export const authRoutes: WsAuthRoute[] = [];diff --git a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.tsx b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.tsxindex 601392f9bb..879db5f27a 100644--- a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.tsx+++ b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.tsx@@ -8,6 +8,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2025-01-04T11:01:50.091Z";export const siteName = "";diff --git a/fixtures/react-router-vercel/app/__generated__/_index.tsx b/fixtures/react-router-vercel/app/__generated__/_index.tsxindex 240d73c36a..7e9af1e569 100644--- a/fixtures/react-router-vercel/app/__generated__/_index.tsx+++ b/fixtures/react-router-vercel/app/__generated__/_index.tsx@@ -15,6 +15,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2025-01-04T11:01:50.091Z";export const siteName = "";diff --git a/fixtures/react-router-vercel/app/root.tsx b/fixtures/react-router-vercel/app/root.tsxindex bfd174e842..85f70e95ed 100644--- a/fixtures/react-router-vercel/app/root.tsx+++ b/fixtures/react-router-vercel/app/root.tsx@@ -1,10 +1,24 @@/* eslint-disable @typescript-eslint/ban-ts-comment */-import { Links, Meta, Outlet, useMatches } from "react-router";+import {+ type HeadersFunction,+ Links,+ Meta,+ Outlet,+ useMatches,+} from "react-router";// @todo think about how to make __generated__ typeable// @ts-ignoreimport { CustomCode, projectId, lastPublished } from "./__generated__/_index";+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }++ return {};+};+const Root = () => {// Get language from matchesconst matches = useMatches();diff --git a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsxindex b090c5c4f0..5eaf5d45f9 100644--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsxindex 2aed2df25e..c2af338d90 100644--- a/fixtures/react-router-vercel/app/routes/_index.tsx+++ b/fixtures/react-router-vercel/app/routes/_index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/react-router-vercel/package.json b/fixtures/react-router-vercel/package.jsonindex 297806f61e..4b02039338 100644--- a/fixtures/react-router-vercel/package.json+++ b/fixtures/react-router-vercel/package.json@@ -27,7 +27,8 @@"react-dom": "18.3.0-canary-14898b6a9-20240318","react-router": "^7.5.3","vite": "^6.3.4",- "webstudio": "workspace:*"+ "webstudio": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*"},"private": true,"type": "module",diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/auth.json b/fixtures/ssg-cloudflare-pages/.webstudio/auth.jsonnew file mode 100644index 0000000000..6672d64b72--- /dev/null+++ b/fixtures/ssg-cloudflare-pages/.webstudio/auth.json@@ -0,0 +1,4 @@+{+ "version": 1,+ "routes": {}+}diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.wsauth.server.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.wsauth.server.tsnew file mode 100644index 0000000000..5b5c11d290--- /dev/null+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.wsauth.server.ts@@ -0,0 +1,3 @@+import type { WsAuthRoute } from "@webstudio-is/wsauth";++export const authRoutes: WsAuthRoute[] = [];diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.tsxindex 8e4354a756..d0639b2eb5 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.tsx@@ -10,6 +10,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2024-07-29T12:50:07.515Z";export const siteName = "";diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsxindex 75cee8b514..59fb5e41cc 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx@@ -13,6 +13,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2024-07-29T12:50:07.515Z";export const siteName = "";diff --git a/fixtures/ssg-cloudflare-pages/package.json b/fixtures/ssg-cloudflare-pages/package.jsonindex 5ec3142340..d05f3d9217 100644--- a/fixtures/ssg-cloudflare-pages/package.json+++ b/fixtures/ssg-cloudflare-pages/package.json@@ -40,6 +40,7 @@"@webstudio-is/sdk-components-react-remix": "workspace:*","react": "18.3.0-canary-14898b6a9-20240318","react-dom": "18.3.0-canary-14898b6a9-20240318",- "vike": "^0.4.229"+ "vike": "^0.4.229",+ "@webstudio-is/wsauth": "workspace:*"}}diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/auth.json b/fixtures/ssg-netlify-by-project-id/.webstudio/auth.jsonnew file mode 100644index 0000000000..6672d64b72--- /dev/null+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/auth.json@@ -0,0 +1,4 @@+{+ "version": 1,+ "routes": {}+}diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.wsauth.server.ts b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.wsauth.server.tsnew file mode 100644index 0000000000..5b5c11d290--- /dev/null+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/$resources.wsauth.server.ts@@ -0,0 +1,3 @@+import type { WsAuthRoute } from "@webstudio-is/wsauth";++export const authRoutes: WsAuthRoute[] = [];diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsxindex 933161117c..16dd018a72 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.tsx@@ -6,6 +6,8 @@ import { useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";export const projectId = "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e";+export const projectDomain = "fixture-client-do-not-touch-wsmel";+export const lastPublished = "2026-01-04T10:46:48.415Z";export const siteName = undefined;diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsxindex 2954d2e601..fb78075778 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx@@ -10,6 +10,8 @@ import {export const projectId = "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e";+export const projectDomain = "fixture-client-do-not-touch-wsmel";+export const lastPublished = "2026-01-04T10:46:48.415Z";export const siteName = undefined;diff --git a/fixtures/ssg-netlify-by-project-id/package.json b/fixtures/ssg-netlify-by-project-id/package.jsonindex 0646a4b404..6e06c7d40e 100644--- a/fixtures/ssg-netlify-by-project-id/package.json+++ b/fixtures/ssg-netlify-by-project-id/package.json@@ -40,6 +40,7 @@"@webstudio-is/sdk-components-react-remix": "workspace:*","react": "18.3.0-canary-14898b6a9-20240318","react-dom": "18.3.0-canary-14898b6a9-20240318",- "vike": "^0.4.229"+ "vike": "^0.4.229",+ "@webstudio-is/wsauth": "workspace:*"}}diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/auth.json b/fixtures/webstudio-cloudflare-template/.webstudio/auth.jsonnew file mode 100644index 0000000000..6672d64b72--- /dev/null+++ b/fixtures/webstudio-cloudflare-template/.webstudio/auth.json@@ -0,0 +1,4 @@+{+ "version": 1,+ "routes": {}+}diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.wsauth.server.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.wsauth.server.tsnew file mode 100644index 0000000000..5b5c11d290--- /dev/null+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.wsauth.server.ts@@ -0,0 +1,3 @@+import type { WsAuthRoute } from "@webstudio-is/wsauth";++export const authRoutes: WsAuthRoute[] = [];diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.tsxindex db3d4f9536..99ca4f29a0 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.tsx@@ -8,6 +8,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2024-07-29T12:50:07.515Z";export const siteName = "";diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsxindex 513c7510b6..d9ef7b52e4 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx@@ -15,6 +15,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectDomain = "cli-basic-test-d0osr";+export const lastPublished = "2024-07-29T12:50:07.515Z";export const siteName = "";diff --git a/fixtures/webstudio-cloudflare-template/app/root.tsx b/fixtures/webstudio-cloudflare-template/app/root.tsxindex 0db0ea97e0..b79380efc1 100644--- a/fixtures/webstudio-cloudflare-template/app/root.tsx+++ b/fixtures/webstudio-cloudflare-template/app/root.tsx@@ -1,10 +1,19 @@/* eslint-disable @typescript-eslint/ban-ts-comment */import { Links, Meta, Outlet, useMatches } from "@remix-run/react";+import type { HeadersFunction } from "@remix-run/server-runtime";// @todo think about how to make __generated__ typeable// @ts-ignoreimport { CustomCode, projectId, lastPublished } from "./__generated__/_index";+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }++ return {};+};+const Root = () => {// Get language from matchesconst matches = useMatches();diff --git a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsxindex 6d1a022011..97be41a9f6 100644--- a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx@@ -17,6 +17,7 @@ import {formIdFieldName,formBotFieldName,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -25,6 +26,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -42,6 +44,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -83,6 +104,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -133,13 +156,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -220,6 +248,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsxindex 8c6db28bba..c05c5a107d 100644--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx@@ -17,6 +17,7 @@ import {formIdFieldName,formBotFieldName,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -25,6 +26,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -42,6 +44,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -83,6 +104,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -133,13 +156,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -220,6 +248,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-cloudflare-template/package.json b/fixtures/webstudio-cloudflare-template/package.jsonindex 3f8635d67d..09d1bed872 100644--- a/fixtures/webstudio-cloudflare-template/package.json+++ b/fixtures/webstudio-cloudflare-template/package.json@@ -39,6 +39,7 @@"@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/sdk-components-react-radix": "workspace:*","@webstudio-is/sdk-components-react-remix": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*","isbot": "^5.1.25","react": "18.3.0-canary-14898b6a9-20240318","react-dom": "18.3.0-canary-14898b6a9-20240318",diff --git a/fixtures/webstudio-features/.template/package.json b/fixtures/webstudio-features/.template/package.jsonindex 85ed77245f..fddf1bd5d9 100644--- a/fixtures/webstudio-features/.template/package.json+++ b/fixtures/webstudio-features/.template/package.json@@ -7,6 +7,7 @@"@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/sdk-components-react-radix": "workspace:*","@webstudio-is/sdk-components-react-router": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*","webstudio": "workspace:*"},"devDependencies": {diff --git a/fixtures/webstudio-features/.webstudio/auth.json b/fixtures/webstudio-features/.webstudio/auth.jsonnew file mode 100644index 0000000000..6672d64b72--- /dev/null+++ b/fixtures/webstudio-features/.webstudio/auth.json@@ -0,0 +1,4 @@+{+ "version": 1,+ "routes": {}+}diff --git a/fixtures/webstudio-features/app/__generated__/$resources.wsauth.server.ts b/fixtures/webstudio-features/app/__generated__/$resources.wsauth.server.tsnew file mode 100644index 0000000000..5b5c11d290--- /dev/null+++ b/fixtures/webstudio-features/app/__generated__/$resources.wsauth.server.ts@@ -0,0 +1,3 @@+import type { WsAuthRoute } from "@webstudio-is/wsauth";++export const authRoutes: WsAuthRoute[] = [];diff --git a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.tsxindex 4ab92a17d1..570ee8537a 100644--- a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.tsx@@ -8,6 +8,8 @@ import { Image as Image } from "@webstudio-is/sdk-components-react";export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[animations]._index.tsx b/fixtures/webstudio-features/app/__generated__/[animations]._index.tsxindex 0d4e7a67f8..2b8a4d0fe6 100644--- a/fixtures/webstudio-features/app/__generated__/[animations]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[animations]._index.tsx@@ -15,6 +15,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[assets1]._index.tsx b/fixtures/webstudio-features/app/__generated__/[assets1]._index.tsxindex b1f3810b02..78ee3101c1 100644--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.tsx@@ -7,6 +7,8 @@ import { Body as Body } from "@webstudio-is/sdk-components-react-router";export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[class-names]._index.tsx b/fixtures/webstudio-features/app/__generated__/[class-names]._index.tsxindex 847f7fa20a..56bbffbc7e 100644--- a/fixtures/webstudio-features/app/__generated__/[class-names]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[class-names]._index.tsx@@ -8,6 +8,8 @@ import { Box as Box } from "@webstudio-is/sdk-components-react";export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[content-block]._index.tsx b/fixtures/webstudio-features/app/__generated__/[content-block]._index.tsxindex bfc23d4ab0..498f2e2513 100644--- a/fixtures/webstudio-features/app/__generated__/[content-block]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[content-block]._index.tsx@@ -12,6 +12,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[duration]._index.tsx b/fixtures/webstudio-features/app/__generated__/[duration]._index.tsxindex dc53e0629a..ebba89d6bc 100644--- a/fixtures/webstudio-features/app/__generated__/[duration]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[duration]._index.tsx@@ -9,6 +9,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[expressions]._index.tsx b/fixtures/webstudio-features/app/__generated__/[expressions]._index.tsxindex f82ba859ee..682f0afc25 100644--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.tsx@@ -12,6 +12,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[form]._index.tsx b/fixtures/webstudio-features/app/__generated__/[form]._index.tsxindex 7c704829c0..d17341725d 100644--- a/fixtures/webstudio-features/app/__generated__/[form]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.tsx@@ -17,6 +17,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.tsx b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.tsxindex afdbceba5b..2d798da808 100644--- a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.tsx@@ -17,6 +17,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.tsxindex 23f046e77f..024d1986eb 100644--- a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.tsx@@ -8,6 +8,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.tsxindex 16d5b0ee72..1605aaecf9 100644--- a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.tsx@@ -8,6 +8,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[radix]._index.tsx b/fixtures/webstudio-features/app/__generated__/[radix]._index.tsxindex 6cd6a7c62b..efa400f9a5 100644--- a/fixtures/webstudio-features/app/__generated__/[radix]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[radix]._index.tsx@@ -19,6 +19,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.tsxindex 1e84b99fc0..430acda063 100644--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx@@ -11,6 +11,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsxindex 20b416a9a7..0ce95c387a 100644--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx@@ -10,6 +10,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.tsx b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.tsxindex 7a0b99c428..b19b9cfe78 100644--- a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.tsx+++ b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.tsx@@ -12,6 +12,8 @@ import { Heading as Heading } from "@webstudio-is/sdk-components-react";export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/__generated__/_index.tsx b/fixtures/webstudio-features/app/__generated__/_index.tsxindex c01c55a379..7a963c48d5 100644--- a/fixtures/webstudio-features/app/__generated__/_index.tsx+++ b/fixtures/webstudio-features/app/__generated__/_index.tsx@@ -18,6 +18,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectDomain = "webstudio-fixture-project-a-0su3o";+export const lastPublished = "2026-01-15T16:19:55.574Z";export const siteName = "KittyGuardedZone";diff --git a/fixtures/webstudio-features/app/root.tsx b/fixtures/webstudio-features/app/root.tsxindex bfd174e842..85f70e95ed 100644--- a/fixtures/webstudio-features/app/root.tsx+++ b/fixtures/webstudio-features/app/root.tsx@@ -1,10 +1,24 @@/* eslint-disable @typescript-eslint/ban-ts-comment */-import { Links, Meta, Outlet, useMatches } from "react-router";+import {+ type HeadersFunction,+ Links,+ Meta,+ Outlet,+ useMatches,+} from "react-router";// @todo think about how to make __generated__ typeable// @ts-ignoreimport { CustomCode, projectId, lastPublished } from "./__generated__/_index";+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }++ return {};+};+const Root = () => {// Get language from matchesconst matches = useMatches();diff --git a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsxindex c4dbfa2841..adb788491a 100644--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsxindex b69e97ac2a..56b8a29228 100644--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx b/fixtures/webstudio-features/app/routes/[assets1]._index.tsxindex 8e20af293b..c2b6dde9d3 100644--- a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsxindex 3027094b47..5541f99088 100644--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsxindex 1d6413738c..c0ac6de1a7 100644--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsxindex d951ffeff1..fd26ce703b 100644--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsxindex 1caffd85d4..70ef8f2041 100644--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsxindex 58a479a6f5..baa2370954 100644--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsxindex 59f17b5699..3d01e5b8f5 100644--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsxindex 1bcdfd80bd..acc8653ce4 100644--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsxindex c55e7a3776..a7b2bda0d6 100644--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsxindex e61045515d..dc2226bd0b 100644--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsxindex 5c1be48481..9f29bca90d 100644--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsxindex bc760b95f1..14ef8fba33 100644--- a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx@@ -1,11 +1,16 @@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 {ReactSdkContext,xmlNodeTagSuffix,} from "@webstudio-is/react-sdk/runtime";-import { Page, breakpoints } from "../__generated__/[sitemap.xml]._index";+import {+ Page,+ breakpoints,+ projectDomain,+} from "../__generated__/[sitemap.xml]._index";import {getPageMeta,getRemixParams,@@ -14,6 +19,25 @@ import {import { assetBaseUrl, imageLoader } from "../constants.mjs";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -55,6 +79,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -112,6 +138,10 @@ export const loader = async (arg: LoaderFunctionArgs) => {text = text.replaceAll(xmlNodeTagSuffix, "");return new Response(`<?xml version="1.0" encoding="UTF-8"?>\n${text}`, {- headers: { "Content-Type": "application/xml" },+ headers: {+ "Content-Type": "application/xml",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",+ },});};diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsxindex b0474c263b..aba9fc9581 100644--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsxindex 2aed2df25e..c2af338d90 100644--- a/fixtures/webstudio-features/app/routes/_index.tsx+++ b/fixtures/webstudio-features/app/routes/_index.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "../constants.mjs";import css from "../__generated__/index.css?url";import { sitemap } from "../__generated__/$resources.sitemap.xml";import { assets } from "../__generated__/$resources.assets";+import { authRoutes } from "../__generated__/$resources.wsauth.server";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/fixtures/webstudio-features/package.json b/fixtures/webstudio-features/package.jsonindex 3f4284d6a2..b7078b607a 100644--- a/fixtures/webstudio-features/package.json+++ b/fixtures/webstudio-features/package.json@@ -28,7 +28,8 @@"react-dom": "18.3.0-canary-14898b6a9-20240318","react-router": "^7.5.3","vite": "^6.3.4",- "webstudio": "workspace:*"+ "webstudio": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*"},"devDependencies": {"@types/react": "^18.2.70",diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 2174c13ab5..2a45e7cec5 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -78,6 +78,7 @@"@webstudio-is/sdk-components-react-remix": "workspace:*","@webstudio-is/sdk-components-react-router": "workspace:*","@webstudio-is/tsconfig": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*","h3": "^1.15.1","ipx": "^3.0.3","isbot": "^5.1.25",diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex d1652faa2a..aca1e43ec8 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -31,6 +31,7 @@ import type {Asset,Resource,WsComponentMeta,+ Pages,} from "@webstudio-is/sdk";import {createScope,@@ -50,6 +51,7 @@ import {getAssetUrl,toRuntimeAsset,} from "@webstudio-is/sdk";+import { createWsAuthResources } from "@webstudio-is/wsauth";import { migratePages } from "@webstudio-is/project-migrations/pages";import type { Data } from "@webstudio-is/http-client";import { LOCAL_DATA_FILE } from "./config";@@ -66,6 +68,7 @@ import { createFramework as createVikeSsgFramework } from "./framework-vike-ssg"import { compareMedia } from "@webstudio-is/css-engine";const limit = pLimit(10);+const wsAuthFile = ".webstudio/auth.json";type SiteDataByPage = {[id: Page["id"]]: {@@ -148,6 +151,40 @@ const mergeJsonInto = async (sourcePath: string, destinationPath: string) => {await writeFile(destinationPath, content, "utf8");};+const writeWsAuthResources = async (generatedDir: string, pages: Pages) => {+ console.info("[wsauth] prebuild create auth config", {+ file: wsAuthFile,+ projectAuthContentLength: pages.meta?.auth?.length ?? 0,+ projectAuthContent: pages.meta?.auth,+ pages: getAllPages(pages).map((page) => ({+ id: page.id,+ name: page.name,+ route: getPagePath(page.id, pages),+ auth: page.meta.auth,+ })),+ });+ const { content, module } = createWsAuthResources({+ projectContent: pages.meta?.auth,+ pages: getAllPages(pages).map((page) => ({+ route: getPagePath(page.id, pages),+ auth: page.meta.auth,+ })),+ });+ console.info("[wsauth] prebuild write auth config", {+ file: wsAuthFile,+ contentLength: content.length,+ content,+ generatedModulePath: join(generatedDir, "$resources.wsauth.server.ts"),+ generatedModule: module,+ });+ await createFolderIfNotExists(dirname(wsAuthFile));+ await writeFile(wsAuthFile, content);+ await createFileIfNotExists(+ join(generatedDir, "$resources.wsauth.server.ts"),+ module+ );+};+/*** Check if template is internal cli template or external path*/@@ -294,6 +331,7 @@ export const prebuild = async (options: {);const pages = migratePages(siteData.build.pages);const allPages = getAllPages(pages);+ await writeWsAuthResources(generatedDir, pages);const siteDataByPage: SiteDataByPage = {};const fontAssetsByPage: Record<Page["id"], string[]> = {};const backgroundImageAssetsByPage: Record<Page["id"], string[]> = {};@@ -602,6 +640,8 @@ export const prebuild = async (options: {export const projectId = "${siteData.build.projectId}";+ export const projectDomain = ${JSON.stringify(siteData.projectDomain)};+export const lastPublished = "${new Date(siteData.build.createdAt).toISOString()}";export const siteName = ${JSON.stringify(projectMeta?.siteName)};@@ -699,6 +739,10 @@ export const prebuild = async (options: {"__ASSETS__",importFrom(`./app/__generated__/$resources.assets`, file))+ .replaceAll(+ "__AUTH__",+ importFrom(`./app/__generated__/$resources.wsauth.server`, file)+ ).replaceAll("__CLIENT__",importFrom(`./app/__generated__/${generatedBasename}`, file)diff --git a/packages/cli/templates/cloudflare/package.json b/packages/cli/templates/cloudflare/package.jsonindex 2ed64821c3..5a36a7b259 100644--- a/packages/cli/templates/cloudflare/package.json+++ b/packages/cli/templates/cloudflare/package.json@@ -12,6 +12,7 @@"build-cf-types": "wrangler types"},"dependencies": {+ "@webstudio-is/wsauth": "0.0.0-webstudio-version","@remix-run/cloudflare": "2.16.5","@remix-run/cloudflare-pages": "2.16.5"},diff --git a/packages/cli/templates/defaults/app/root.tsx b/packages/cli/templates/defaults/app/root.tsxindex 0db0ea97e0..b79380efc1 100644--- a/packages/cli/templates/defaults/app/root.tsx+++ b/packages/cli/templates/defaults/app/root.tsx@@ -1,10 +1,19 @@/* eslint-disable @typescript-eslint/ban-ts-comment */import { Links, Meta, Outlet, useMatches } from "@remix-run/react";+import type { HeadersFunction } from "@remix-run/server-runtime";// @todo think about how to make __generated__ typeable// @ts-ignoreimport { CustomCode, projectId, lastPublished } from "./__generated__/_index";+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }++ return {};+};+const Root = () => {// Get language from matchesconst matches = useMatches();diff --git a/packages/cli/templates/defaults/app/route-templates/html.tsx b/packages/cli/templates/defaults/app/route-templates/html.tsxindex 74ff66addd..6eb6087392 100644--- a/packages/cli/templates/defaults/app/route-templates/html.tsx+++ b/packages/cli/templates/defaults/app/route-templates/html.tsx@@ -17,6 +17,7 @@ import {formIdFieldName,formBotFieldName,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -25,6 +26,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -42,6 +44,25 @@ import * as constants from "__CONSTANTS__";import css from "__CSS__?url";import { sitemap } from "__SITEMAP__";import { assets } from "__ASSETS__";+import { authRoutes } from "__AUTH__";++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") {@@ -83,6 +104,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -133,13 +156,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -220,6 +248,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/packages/cli/templates/defaults/app/route-templates/xml.tsx b/packages/cli/templates/defaults/app/route-templates/xml.tsxindex 0617d1fd39..17cecc3c6c 100644--- a/packages/cli/templates/defaults/app/route-templates/xml.tsx+++ b/packages/cli/templates/defaults/app/route-templates/xml.tsx@@ -1,15 +1,35 @@import { renderToString } from "react-dom/server";import { type LoaderFunctionArgs, redirect } from "@remix-run/server-runtime";import { isLocalResource, loadResources } from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,xmlNodeTagSuffix,} from "@webstudio-is/react-sdk/runtime";-import { Page, breakpoints } from "__CLIENT__";+import { Page, breakpoints, projectDomain } from "__CLIENT__";import { getPageMeta, getRemixParams, getResources } from "__SERVER__";import { assetBaseUrl, imageLoader } from "__CONSTANTS__";import { sitemap } from "__SITEMAP__";import { assets } from "__ASSETS__";+import { authRoutes } from "__AUTH__";++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") {@@ -51,6 +71,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -104,6 +126,10 @@ export const loader = async (arg: LoaderFunctionArgs) => {text = text.replaceAll(xmlNodeTagSuffix, "");return new Response(`<?xml version="1.0" encoding="UTF-8"?>\n${text}`, {- headers: { "Content-Type": "application/xml" },+ headers: {+ "Content-Type": "application/xml",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",+ },});};diff --git a/packages/cli/templates/defaults/package.json b/packages/cli/templates/defaults/package.jsonindex da57824989..ada1b9d03f 100644--- a/packages/cli/templates/defaults/package.json+++ b/packages/cli/templates/defaults/package.json@@ -18,6 +18,7 @@"@webstudio-is/sdk-components-animation": "0.0.0-webstudio-version","@webstudio-is/sdk-components-react-radix": "0.0.0-webstudio-version","@webstudio-is/sdk-components-react-remix": "0.0.0-webstudio-version",+ "@webstudio-is/wsauth": "0.0.0-webstudio-version","isbot": "^5.1.25","react": "18.3.0-canary-14898b6a9-20240318","react-dom": "18.3.0-canary-14898b6a9-20240318"diff --git a/packages/cli/templates/internal/package.json b/packages/cli/templates/internal/package.jsonindex bf1cadeaab..0647aeb838 100644--- a/packages/cli/templates/internal/package.json+++ b/packages/cli/templates/internal/package.json@@ -6,6 +6,7 @@"@webstudio-is/sdk-components-animation": "workspace:*","@webstudio-is/sdk-components-react": "workspace:*","@webstudio-is/sdk-components-react-radix": "workspace:*",- "@webstudio-is/sdk-components-react-remix": "workspace:*"+ "@webstudio-is/sdk-components-react-remix": "workspace:*",+ "@webstudio-is/wsauth": "workspace:*"}}diff --git a/packages/cli/templates/react-router-cloudflare/package.json b/packages/cli/templates/react-router-cloudflare/package.jsonindex 959581cded..fb4f6b7a55 100644--- a/packages/cli/templates/react-router-cloudflare/package.json+++ b/packages/cli/templates/react-router-cloudflare/package.json@@ -7,6 +7,7 @@},"dependencies": {"@cloudflare/vite-plugin": "^1.1.0",+ "@webstudio-is/wsauth": "0.0.0-webstudio-version","wrangler": "^4.14.1"}}diff --git a/packages/cli/templates/react-router/app/root.tsx b/packages/cli/templates/react-router/app/root.tsxindex bfd174e842..85f70e95ed 100644--- a/packages/cli/templates/react-router/app/root.tsx+++ b/packages/cli/templates/react-router/app/root.tsx@@ -1,10 +1,24 @@/* eslint-disable @typescript-eslint/ban-ts-comment */-import { Links, Meta, Outlet, useMatches } from "react-router";+import {+ type HeadersFunction,+ Links,+ Meta,+ Outlet,+ useMatches,+} from "react-router";// @todo think about how to make __generated__ typeable// @ts-ignoreimport { CustomCode, projectId, lastPublished } from "./__generated__/_index";+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }++ return {};+};+const Root = () => {// Get language from matchesconst matches = useMatches();diff --git a/packages/cli/templates/react-router/app/route-templates/html.tsx b/packages/cli/templates/react-router/app/route-templates/html.tsxindex 0ce5fe4f6c..fd79a5de94 100644--- a/packages/cli/templates/react-router/app/route-templates/html.tsx+++ b/packages/cli/templates/react-router/app/route-templates/html.tsx@@ -17,6 +17,7 @@ import {formBotFieldName,cachedFetch,} from "@webstudio-is/sdk/runtime";+import { authenticateRequest } from "@webstudio-is/wsauth";import {ReactSdkContext,PageSettingsMeta,@@ -24,6 +25,7 @@ import {} from "@webstudio-is/react-sdk/runtime";import {projectId,+ projectDomain,Page,siteName,favIconAsset,@@ -41,6 +43,25 @@ import * as constants from "__CONSTANTS__";import css from "__CSS__?url";import { sitemap } from "__SITEMAP__";import { assets } from "__ASSETS__";+import { authRoutes } from "__AUTH__";++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") {@@ -82,6 +103,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -132,13 +155,18 @@ export const loader = async (arg: LoaderFunctionArgs) => {{status: pageMeta.status,headers: {- "Cache-Control": "public, max-age=600",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",},});};-export const headers: HeadersFunction = () => {+export const headers: HeadersFunction = ({ errorHeaders }) => {+ if (errorHeaders) {+ return errorHeaders;+ }+return {"Cache-Control": "public, max-age=0, must-revalidate",};@@ -219,6 +247,8 @@ export const action = async ({}: ActionFunctionArgs): Promise<{ success: true } | { success: false; errors: string[] }> => {+ authenticateProductionRequest(request);+try {const url = new URL(request.url);url.host = getRequestHost(request);diff --git a/packages/cli/templates/react-router/app/route-templates/xml.tsx b/packages/cli/templates/react-router/app/route-templates/xml.tsxindex 9785f66700..ccc93691c4 100644--- a/packages/cli/templates/react-router/app/route-templates/xml.tsx+++ b/packages/cli/templates/react-router/app/route-templates/xml.tsx@@ -1,15 +1,35 @@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 {ReactSdkContext,xmlNodeTagSuffix,} from "@webstudio-is/react-sdk/runtime";-import { Page, breakpoints } from "__CLIENT__";+import { Page, breakpoints, projectDomain } from "__CLIENT__";import { getPageMeta, getRemixParams, getResources } from "__SERVER__";import { assetBaseUrl, imageLoader } from "__CONSTANTS__";import { sitemap } from "__SITEMAP__";import { assets } from "__ASSETS__";+import { authRoutes } from "__AUTH__";++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") {@@ -51,6 +71,8 @@ const customFetch: typeof fetch = (input, init) => {};export const loader = async (arg: LoaderFunctionArgs) => {+ const authRoute = authenticateProductionRequest(arg.request);+const url = new URL(arg.request.url);const host =arg.request.headers.get("x-forwarded-host") ||@@ -108,6 +130,10 @@ export const loader = async (arg: LoaderFunctionArgs) => {text = text.replaceAll(xmlNodeTagSuffix, "");return new Response(`<?xml version="1.0" encoding="UTF-8"?>\n${text}`, {- headers: { "Content-Type": "application/xml" },+ headers: {+ "Content-Type": "application/xml",+ "Cache-Control":+ authRoute === undefined ? "public, max-age=600" : "private, no-store",+ },});};diff --git a/packages/cli/templates/react-router/package.json b/packages/cli/templates/react-router/package.jsonindex 46263c9fd1..4ffc965704 100644--- a/packages/cli/templates/react-router/package.json+++ b/packages/cli/templates/react-router/package.json@@ -17,6 +17,7 @@"@webstudio-is/sdk-components-react-radix": "0.0.0-webstudio-version","@webstudio-is/sdk-components-react-router": "0.0.0-webstudio-version","@webstudio-is/sdk-components-react": "0.0.0-webstudio-version",+ "@webstudio-is/wsauth": "0.0.0-webstudio-version","isbot": "^5.1.25","react": "18.3.0-canary-14898b6a9-20240318","react-dom": "18.3.0-canary-14898b6a9-20240318",diff --git a/packages/design-system/src/components/pro-badge.tsx b/packages/design-system/src/components/pro-badge.tsxindex fc3292d570..371512a376 100644--- a/packages/design-system/src/components/pro-badge.tsx+++ b/packages/design-system/src/components/pro-badge.tsx@@ -1,12 +1,14 @@import type { ReactNode } from "react";import { css, theme, type CSS } from "../stitches.config";-import { Text } from "./text";+import { textVariants } from "./text";-const style = css({- display: "inline-flex",+const pricingUrl = "https://webstudio.is/pricing";++const style = css(textVariants.labels, {+ display: "inline-grid",+ placeItems: "center",borderRadius: theme.borderRadius[3],px: theme.spacing[3],- py: theme.spacing[1],height: theme.spacing[9],color: theme.colors.foregroundContrastMain,alignItems: "center",@@ -16,6 +18,17 @@ const style = css({// @todo doesn't work in tooltips, needs a workaroundtextOverflow: "ellipsis",background: theme.colors.foregroundTextSubtle,+ textDecoration: "none",+ cursor: "pointer",+ pointerEvents: "auto",+ "&:focus-visible": {+ outline: `2px solid ${theme.colors.borderFocus}`,+ outlineOffset: 1,+ },+ "@supports (text-box-trim: trim-both) and (text-box-edge: cap alphabetic)": {+ textBoxTrim: "trim-both",+ textBoxEdge: "cap alphabetic",+ },});export const ProBadge = ({@@ -25,5 +38,14 @@ export const ProBadge = ({children: ReactNode;css?: CSS;}) => {- return <Text className={style({ css })}>{children}</Text>;+ return (+ <a+ className={style({ css })}+ href={pricingUrl}+ target="_blank"+ rel="noreferrer"+ >+ {children}+ </a>+ );};diff --git a/packages/design-system/src/test-setup.ts b/packages/design-system/src/test-setup.tsindex 926c76ed97..f55258a624 100644--- a/packages/design-system/src/test-setup.ts+++ b/packages/design-system/src/test-setup.ts@@ -6,3 +6,9 @@ const g = globalThis as any;if (typeof g.CSS === "undefined") {g.CSS = { supports: () => false };}++// jsdom does not implement canvas, while hdr-color-input touches getContext+// during module evaluation through the design-system barrel import.+if (g.HTMLCanvasElement !== undefined) {+ g.HTMLCanvasElement.prototype.getContext = () => null;+}diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex a904bd02f3..1fa68c025c 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -36,6 +36,7 @@ export type Data = {deployment?: Deployment | undefined;};assets: Array<Asset>;+ projectDomain?: string;origin?: string;};diff --git a/packages/plans/src/plan-client.server.test.ts b/packages/plans/src/plan-client.server.test.tsindex 70051a8e51..446e79b526 100644--- a/packages/plans/src/plan-client.server.test.ts+++ b/packages/plans/src/plan-client.server.test.ts@@ -149,6 +149,7 @@ const fullFeatures: PlanFeatures = {canRestoreBackups: true,allowAdditionalPermissions: true,allowDynamicData: true,+ allowAuth: true,allowContentMode: true,allowStagingPublish: true,maxContactEmailsPerProject: 5,diff --git a/packages/plans/src/plan-features.test.ts b/packages/plans/src/plan-features.test.tsindex 00db820d42..bc8e385101 100644--- a/packages/plans/src/plan-features.test.ts+++ b/packages/plans/src/plan-features.test.ts@@ -13,6 +13,7 @@ const fullFeatures: PlanFeatures = {canRestoreBackups: true,allowAdditionalPermissions: true,allowDynamicData: true,+ allowAuth: true,allowContentMode: true,allowStagingPublish: true,maxContactEmailsPerProject: 5,diff --git a/packages/plans/src/plan-features.ts b/packages/plans/src/plan-features.tsindex ef06b01c8d..9122c06dc5 100644--- a/packages/plans/src/plan-features.ts+++ b/packages/plans/src/plan-features.ts@@ -10,6 +10,7 @@ export const PlanFeaturesSchema = z.object({canRestoreBackups: z.boolean(),allowAdditionalPermissions: z.boolean(),allowDynamicData: z.boolean(),+ allowAuth: z.boolean(),allowContentMode: z.boolean(),allowStagingPublish: z.boolean(),maxContactEmailsPerProject: z.number().nonnegative(),@@ -37,6 +38,7 @@ export const defaultPlanFeatures: PlanFeatures = {canRestoreBackups: false,allowAdditionalPermissions: false,allowDynamicData: false,+ allowAuth: false,allowContentMode: false,allowStagingPublish: false,maxContactEmailsPerProject: 0,diff --git a/packages/react-sdk/placeholder.d.ts b/packages/react-sdk/placeholder.d.tsindex bd7346066d..572686dc06 100644--- a/packages/react-sdk/placeholder.d.ts+++ b/packages/react-sdk/placeholder.d.ts@@ -10,6 +10,8 @@ declare module "__CLIENT__" {export const projectId: string;+ export const projectDomain: string | undefined;+export const lastPublished: string;export const siteName: string;@@ -51,6 +53,11 @@ declare module "__SERVER__" {export const contactEmail: undefined | string;}+declare module "__AUTH__" {+ import type { WsAuthRoute } from "@webstudio-is/wsauth";+ export const authRoutes: WsAuthRoute[];+}+declare module "__SITEMAP__" {export const sitemap: Array<{path: string;diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 50933f7a03..4c8a7ec76f 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -55,7 +55,8 @@"reserved-identifiers": "^1.0.0","type-fest": "^4.37.0","warn-once": "^0.1.1",- "zod": "^3.24.2"+ "zod": "^3.24.2",+ "@webstudio-is/wsauth": "workspace:*"},"devDependencies": {"@webstudio-is/css-data": "workspace:*",diff --git a/packages/sdk/src/schema/pages.test.ts b/packages/sdk/src/schema/pages.test.tsindex d0aebe08f3..6e56d3861f 100644--- a/packages/sdk/src/schema/pages.test.ts+++ b/packages/sdk/src/schema/pages.test.ts@@ -1,5 +1,11 @@import { describe, expect, test } from "vitest";-import { OldPagePath, PagePath, Pages, ProjectNewRedirectPath } from "./pages";+import {+ OldPagePath,+ PageAuth,+ PagePath,+ Pages,+ ProjectNewRedirectPath,+} from "./pages";const validPages = {homePageId: "home",@@ -199,6 +205,57 @@ test("validates root folder is not nested", () => {]);});+describe("PageAuth", () => {+ test("accepts basic auth metadata", () => {+ expect(+ PageAuth.parse({+ method: "basic",+ login: "admin",+ password: "secret",+ })+ ).toEqual({+ method: "basic",+ login: "admin",+ password: "secret",+ });+ });++ test("normalizes legacy basic auth metadata", () => {+ expect(+ PageAuth.parse({+ type: "basic",+ login: "admin",+ password: "secret",+ })+ ).toEqual({+ method: "basic",+ login: "admin",+ password: "secret",+ });+ });++ test("rejects invalid basic auth metadata", () => {+ expect(+ PageAuth.safeParse({+ method: "basic",+ login: "admin:root",+ password: "secret phrase",+ }).error?.issues+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ path: ["login"],+ message: "Login can't contain a colon",+ }),+ expect.objectContaining({+ path: ["password"],+ message: "Password can't contain whitespace",+ }),+ ])+ );+ });+});+test("validates children are registered in only one folder", () => {expect(Pages.safeParse({diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.tsindex fd7a0da730..3fe777f6a5 100644--- a/packages/sdk/src/schema/pages.ts+++ b/packages/sdk/src/schema/pages.ts@@ -1,4 +1,5 @@import { z } from "zod";+import { validateBasicAuth } from "@webstudio-is/wsauth";export type System = {params: Record<string, string | undefined>;@@ -45,6 +46,52 @@ export const PageTitle = zexport const documentTypes = ["html", "xml"] as const;+const BasicAuthFields = {+ login: z.string(),+ password: z.string(),+};++const validateBasicAuthFields = (+ {+ login,+ password,+ }: {+ login: string;+ password: string;+ },+ context: z.RefinementCtx+) => {+ for (const issue of validateBasicAuth({ login, password }).issues ?? []) {+ context.addIssue({+ code: z.ZodIssueCode.custom,+ path: issue.path,+ message: issue.message,+ });+ }+};++const PageBasicAuth = z+ .object({+ method: z.literal("basic"),+ ...BasicAuthFields,+ })+ .superRefine(validateBasicAuthFields);++const LegacyPageBasicAuth = z+ .object({+ type: z.literal("basic"),+ ...BasicAuthFields,+ })+ .superRefine(validateBasicAuthFields)+ .transform(({ login, password }) => ({+ method: "basic" as const,+ login,+ password,+ }));++export const PageAuth = z.union([PageBasicAuth, LegacyPageBasicAuth]);+export type PageAuth = z.infer<typeof PageAuth>;+const commonPageFields = {id: PageId,name: PageName,@@ -62,6 +109,7 @@ const commonPageFields = {status: z.string().optional(),redirect: z.string().optional(),documentType: z.optional(z.enum(documentTypes)),+ auth: PageAuth.optional(),custom: z.array(z.object({@@ -154,6 +202,7 @@ const ProjectMeta = z.object({contactEmail: z.string().optional(),faviconAssetId: z.string().optional(),code: z.string().optional(),+ auth: z.string().optional(),});export type ProjectMeta = z.infer<typeof ProjectMeta>;diff --git a/packages/wsauth/README.md b/packages/wsauth/README.mdnew file mode 100644index 0000000000..aa0575c844--- /dev/null+++ b/packages/wsauth/README.md@@ -0,0 +1,106 @@+# `@webstudio-is/wsauth`++`wsauth` is Webstudio's generic authentication package.++It owns shared authentication types, validators, route matching, build-time+resource generation, and runtime enforcement helpers used by Builder-generated+sites. The package is structured around auth methods so Webstudio can add+methods beyond Basic Auth without changing the route auth model.++The first implemented method is HTTP Basic Auth.++## Auth Config++Webstudio sync writes route authentication config at:++```txt+.webstudio/auth.json+```++Version 1 uses JSON with route strings as keys:++```json+{+ "version": 1,+ "routes": {+ "/my/page": {+ "method": "basic",+ "login": "me",+ "password": "idiot"+ },+ "/bla/*": {+ "method": "basic",+ "login": "bla",+ "password": "blubb"+ }+ }+}+```++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+`.++## Basic Auth++Version 1 supports Basic Auth:++```json+{+ "method": "basic",+ "login": "admin",+ "password": "secret"+}+```++Rules:++- Login is required.+- Password is required.+- Login must not contain `:`.+- Login must not contain whitespace.+- Password must not contain whitespace.+- Password may contain `:`.++The colon rule follows HTTP Basic Auth's `user-id ":" password` credential+structure from RFC 7617.++## Build Semantics++Build tools generate `.webstudio/auth.json` from Webstudio project data. The+file is treated as build output and is overwritten on sync.++Generated auth sources are applied in this order:++1. Project-level auth config from Webstudio project settings+2. Page-level auth generated by Webstudio page settings++If both sources define the same route, the later source wins. Because routes are+JSON object keys, the generated config file cannot represent duplicate routes.++## Runtime++At runtime, protected requests without valid credentials receive:++```ts+new Response("Authentication required", {+ status: 401,+ headers: {+ "WWW-Authenticate": 'Basic realm="Webstudio"',+ "Cache-Control": "private, no-store",+ },+});+```diff --git a/packages/wsauth/package.json b/packages/wsauth/package.jsonnew file mode 100644index 0000000000..1eb19d635e--- /dev/null+++ b/packages/wsauth/package.json@@ -0,0 +1,33 @@+{+ "name": "@webstudio-is/wsauth",+ "version": "0.0.0-webstudio-version",+ "description": "Webstudio auth primitives, validators, build-time helpers, and runtime enforcement",+ "author": "Webstudio <[email protected]>",+ "homepage": "https://webstudio.is",+ "type": "module",+ "scripts": {+ "build": "rm -rf lib && esbuild src/index.ts --outdir=lib --bundle --format=esm --packages=external",+ "dts": "tsc --project tsconfig.dts.json",+ "typecheck": "tsgo --noEmit",+ "test": "vitest run"+ },+ "devDependencies": {+ "@webstudio-is/tsconfig": "workspace:*",+ "vitest": "^3.1.2"+ },+ "exports": {+ ".": {+ "webstudio": "./src/index.ts",+ "types": "./lib/types/index.d.ts",+ "import": "./lib/index.js"+ }+ },+ "files": [+ "lib/*",+ "README.md",+ "!*.{test,stories}.*"+ ],+ "license": "AGPL-3.0-or-later",+ "private": false,+ "sideEffects": false+}diff --git a/packages/wsauth/src/index.test.ts b/packages/wsauth/src/index.test.tsnew file mode 100644index 0000000000..0180997e2c--- /dev/null+++ b/packages/wsauth/src/index.test.ts@@ -0,0 +1,348 @@+import { describe, expect, test } from "vitest";+import {+ authenticateRequest,+ buildWsAuth,+ createBasicAuthRoute,+ createWsAuthResources,+ findWsAuthRoute,+ getBasicAuthCredentials,+ parseWsAuth,+ validateBasicAuth,+ validateWsAuthRoute,+} from "./index";++describe("wsauth", () => {+ test("parses JSON auth config with route keys", () => {+ expect(+ parseWsAuth(+ JSON.stringify({+ version: 1,+ routes: {+ "/my/page": {+ method: "basic",+ login: "me",+ password: "idiot",+ },+ "/bla/*": {+ method: "basic",+ login: "bla",+ password: "blubb",+ },+ },+ })+ )+ ).toEqual({+ routes: [+ {+ route: "/my/page",+ auth: {+ method: "basic",+ login: "me",+ password: "idiot",+ credentials: "me:idiot",+ },+ },+ {+ route: "/bla/*",+ auth: {+ method: "basic",+ login: "bla",+ password: "blubb",+ credentials: "bla:blubb",+ },+ },+ ],+ errors: [],+ });+ });++ test("reports path-specific parse errors", () => {+ expect(+ parseWsAuth(+ JSON.stringify({+ version: 1,+ routes: {+ page: {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ "/empty-password": {+ method: "basic",+ login: "admin",+ password: "",+ },+ "/docs/*/page": {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ },+ })+ ).errors+ ).toEqual([+ {+ path: 'routes."page"',+ message: 'Route must start with "/"',+ },+ {+ path: 'routes."/empty-password".password',+ message: "Password is required",+ },+ {+ path: 'routes."/docs/*/page"',+ message: "Wildcard route segment must be the last segment",+ },+ ]);+ });++ test("validates basic auth fields", () => {+ const emptyResult = validateBasicAuth({ login: "", password: "" });+ expect(emptyResult.issues).toEqual([+ { path: ["login"], message: "Login is required" },+ { path: ["password"], message: "Password is required" },+ ]);+ expect(emptyResult.errors).toEqual({+ login: ["Login is required"],+ password: ["Password is required"],+ });+ const invalidResult = validateBasicAuth({+ login: "admin:root",+ password: "secret phrase",+ });+ expect(invalidResult.issues).toEqual([+ { path: ["login"], message: "Login can't contain a colon" },+ { path: ["password"], message: "Password can't contain whitespace" },+ ]);+ expect(invalidResult.errors).toEqual({+ login: ["Login can't contain a colon"],+ password: ["Password can't contain whitespace"],+ });+ });++ test("validates route syntax", () => {+ expect(validateWsAuthRoute("/private")).toBeUndefined();+ expect(validateWsAuthRoute("/docs/*")).toBeUndefined();+ expect(validateWsAuthRoute("private")).toBe('Route must start with "/"');+ expect(validateWsAuthRoute("/docs/*/page")).toBe(+ "Wildcard route segment must be the last segment"+ );+ });++ test("builds content from JSON and route sources", () => {+ const result = buildWsAuth([+ {+ name: "Auth",+ content: JSON.stringify({+ version: 1,+ routes: {+ "/private": {+ method: "basic",+ login: "first",+ password: "secret",+ },+ },+ }),+ },+ {+ name: "Generated page auth",+ routes: [+ createBasicAuthRoute({+ route: "/private",+ login: "second",+ password: "secret",+ }),+ createBasicAuthRoute({+ route: "/generated",+ login: "page",+ password: "secret",+ }),+ ],+ },+ ]);++ expect(result.routes.map(({ route }) => route)).toEqual([+ "/private",+ "/generated",+ ]);+ expect(JSON.parse(result.content)).toEqual({+ version: 1,+ routes: {+ "/private": {+ method: "basic",+ login: "second",+ password: "secret",+ },+ "/generated": {+ method: "basic",+ login: "page",+ password: "secret",+ },+ },+ });+ });++ test("builds resources from project and page inputs", () => {+ const result = createWsAuthResources({+ projectContent: JSON.stringify({+ version: 1,+ routes: {+ "/project": {+ method: "basic",+ login: "project",+ password: "secret",+ },+ },+ }),+ pages: [+ {+ route: "/project",+ auth: {+ method: "basic",+ login: "page",+ password: "secret",+ },+ },+ {+ route: "/legacy",+ auth: {+ type: "basic",+ login: "legacy",+ password: "secret",+ },+ },+ {+ route: "/public",+ },+ ],+ });++ expect(result.routes.map(({ route }) => route)).toEqual([+ "/project",+ "/legacy",+ ]);+ expect(JSON.parse(result.content)).toEqual({+ version: 1,+ routes: {+ "/project": {+ method: "basic",+ login: "page",+ password: "secret",+ },+ "/legacy": {+ method: "basic",+ login: "legacy",+ password: "secret",+ },+ },+ });+ expect(result.module).toBe(+ [+ `import type { WsAuthRoute } from "@webstudio-is/wsauth";`,+ "",+ `export const authRoutes: WsAuthRoute[] = ${JSON.stringify(+ result.routes,+ null,+ 2+ )};`,+ "",+ ].join("\n")+ );+ });++ test("rejects invalid generated page auth inputs", () => {+ expect(() =>+ createWsAuthResources({+ pages: [+ {+ route: "/private",+ auth: {+ method: "basic",+ login: "",+ password: "secret",+ },+ },+ ],+ })+ ).toThrow(+ 'Basic auth requires non-empty login and password; login cannot contain ":" and neither field can contain whitespace'+ );+ });++ test("matches routes using page route syntax", () => {+ const { routes } = parseWsAuth(+ JSON.stringify({+ version: 1,+ routes: {+ "/": { method: "basic", login: "admin", password: "root" },+ "/blog/:slug": {+ method: "basic",+ login: "writer",+ password: "secret",+ },+ "/docs/*": { method: "basic", login: "docs", password: "secret" },+ },+ })+ );+ expect(findWsAuthRoute(routes, "/")?.route).toBe("/");+ expect(findWsAuthRoute(routes, "/blog/post")?.route).toBe("/blog/:slug");+ expect(findWsAuthRoute(routes, "/docs/api/v1")?.route).toBe("/docs/*");+ expect(findWsAuthRoute(routes, "/public")).toBeUndefined();+ });++ test("extracts basic auth credentials from authorization header", () => {+ expect(getBasicAuthCredentials(`Basic ${btoa("admin:secret")}`)).toBe(+ "admin:secret"+ );+ expect(getBasicAuthCredentials(`basic ${btoa("admin:secret")}`)).toBe(+ "admin:secret"+ );+ expect(getBasicAuthCredentials(`Bearer token`)).toBeUndefined();+ });++ test("enforces basic auth for matching routes", () => {+ const authRoutes = [+ createBasicAuthRoute({+ route: "/private",+ login: "admin",+ password: "secret",+ }),+ ];++ expect(+ authenticateRequest(new Request("https://example.com/public"), authRoutes)+ ).toBeUndefined();+ expect(() =>+ authenticateRequest(+ new Request("https://example.com/private"),+ authRoutes+ )+ ).toThrow(Response);+ expect(+ authenticateRequest(+ new Request("https://example.com/private", {+ headers: {+ Authorization: `Basic ${btoa("admin:secret")}`,+ },+ }),+ authRoutes+ )+ ).toBe(authRoutes[0]);++ try {+ authenticateRequest(+ new Request("https://example.com/private"),+ authRoutes+ );+ } catch (error) {+ expect(error).toBeInstanceOf(Response);+ expect((error as Response).status).toBe(401);+ expect((error as Response).headers.get("WWW-Authenticate")).toBe(+ `Basic realm="Webstudio"`+ );+ expect((error as Response).headers.get("Cache-Control")).toBe(+ "private, no-store"+ );+ }+ });+});diff --git a/packages/wsauth/src/index.ts b/packages/wsauth/src/index.tsnew file mode 100644index 0000000000..61891b38a1--- /dev/null+++ b/packages/wsauth/src/index.ts@@ -0,0 +1,575 @@+export type BasicAuthRule = {+ method: "basic";+ login: string;+ password: string;+ credentials: string;+};++export type AuthRule = BasicAuthRule;++export type WsAuthRoute = {+ route: string;+ auth: AuthRule;+};++export type WsAuthParseError = {+ path: string;+ message: string;+};++export type WsAuthParseResult = {+ routes: WsAuthRoute[];+ errors: WsAuthParseError[];+};++export type WsAuthSource =+ | {+ name: string;+ content: string;+ }+ | {+ name: string;+ routes: WsAuthRoute[];+ };++export type WsAuthBuildResult = {+ routes: WsAuthRoute[];+ content: string;+};++export type WsAuthConfig = {+ version: 1;+ routes: Record<string, BasicAuthInput>;+};++export type BasicAuthInput =+ | {+ method: "basic";+ login: string;+ password: string;+ }+ | {+ type: "basic";+ login: string;+ password: string;+ };++export type WsAuthPageInput = {+ route: string;+ auth?: BasicAuthInput;+};++export type WsAuthResourcesInput = {+ projectContent?: string;+ pages: WsAuthPageInput[];+ projectSourceName?: string;+ generatedSourceName?: string;+};++export type WsAuthResources = WsAuthBuildResult & {+ module: string;+};++export type BasicAuthValidation = {+ auth?: BasicAuthRule;+ issues?: BasicAuthIssue[];+ errors?: {+ login?: string[];+ password?: string[];+ };+};++export type BasicAuthIssue = {+ path: ["login"] | ["password"];+ message: string;+};++const basicLoginErrors = (login: string) => {+ const issues: BasicAuthIssue[] = [];+ if (login.length === 0) {+ issues.push({ path: ["login"], message: "Login is required" });+ }+ if (login.includes(":")) {+ issues.push({ path: ["login"], message: "Login can't contain a colon" });+ }+ if (/\s/.test(login)) {+ issues.push({+ path: ["login"],+ message: "Login can't contain whitespace",+ });+ }+ return issues;+};++const basicPasswordErrors = (password: string) => {+ const issues: BasicAuthIssue[] = [];+ if (password.length === 0) {+ issues.push({ path: ["password"], message: "Password is required" });+ }+ if (/\s/.test(password)) {+ issues.push({+ path: ["password"],+ message: "Password can't contain whitespace",+ });+ }+ return issues;+};++export const validateBasicAuth = ({+ login,+ password,+}: {+ login: string;+ password: string;+}): BasicAuthValidation => {+ const issues = [...basicLoginErrors(login), ...basicPasswordErrors(password)];+ if (issues.length > 0) {+ const loginErrors = issues+ .filter((issue) => issue.path[0] === "login")+ .map((issue) => issue.message);+ const passwordErrors = issues+ .filter((issue) => issue.path[0] === "password")+ .map((issue) => issue.message);+ return {+ issues,+ errors: {+ login: loginErrors.length > 0 ? loginErrors : undefined,+ password: passwordErrors.length > 0 ? passwordErrors : undefined,+ },+ };+ }+ return {+ auth: {+ method: "basic",+ login,+ password,+ credentials: `${login}:${password}`,+ },+ };+};++export const parseBasicAuthExpression = (expression: string) => {+ const separatorIndex = expression.indexOf(":");+ if (separatorIndex === -1) {+ return;+ }+ return validateBasicAuth({+ login: expression.slice(0, separatorIndex),+ password: expression.slice(separatorIndex + 1),+ }).auth;+};++export const createBasicAuthRoute = ({+ route,+ login,+ password,+}: {+ route: string;+ login: string;+ password: string;+}): WsAuthRoute => {+ const routeError = validateWsAuthRoute(route);+ if (routeError) {+ throw new Error(routeError);+ }+ const auth = validateBasicAuth({ login, password }).auth;+ if (auth === undefined) {+ throw new Error(+ 'Basic auth requires non-empty login and password; login cannot contain ":" and neither field can contain whitespace'+ );+ }+ return { route, auth };+};++export const createWsAuthRouteFromPage = ({+ route,+ auth,+}: WsAuthPageInput): WsAuthRoute | undefined => {+ if (auth === undefined) {+ return;+ }+ if (+ ("method" in auth && auth.method !== "basic") ||+ ("type" in auth && auth.type !== "basic")+ ) {+ throw new Error(`Unsupported auth method for route "${route}"`);+ }+ return createBasicAuthRoute({+ route,+ login: auth.login,+ password: auth.password,+ });+};++const isRecord = (value: unknown): value is Record<string, unknown> => {+ return (+ typeof value === "object" &&+ value !== null &&+ Array.isArray(value) === false+ );+};++const parameterSegment = /^:\w+[?*]?$/;++export const validateWsAuthRoute = (route: string) => {+ if (route.startsWith("/") === false) {+ return 'Route must start with "/"';+ }+ if (route === "/") {+ return;+ }+ if (route !== "/" && route.endsWith("/")) {+ return 'Route must not end with "/"';+ }+ if (route.includes("//")) {+ return 'Route must not contain repeating "/"';+ }+ const segments = route.slice(1).split("/");+ for (let index = 0; index < segments.length; index += 1) {+ const segment = segments[index];+ if (segment === undefined || segment === "") {+ return "Route contains an empty segment";+ }+ if (segment === "*" || /^:\w+\*$/.test(segment)) {+ if (index !== segments.length - 1) {+ return "Wildcard route segment must be the last segment";+ }+ continue;+ }+ if (segment.startsWith(":") && parameterSegment.test(segment) === false) {+ return `Invalid route parameter "${segment}"`;+ }+ if (segment.includes("*")) {+ return "Wildcard can only be used as * or :name*";+ }+ }+};++const parseJson = (content: string, errors: WsAuthParseError[]) => {+ if (content.trim() === "") {+ return { version: 1, routes: {} };+ }+ try {+ return JSON.parse(content) as unknown;+ } catch (error) {+ errors.push({+ path: "$",+ message: error instanceof Error ? error.message : "Invalid JSON",+ });+ }+};++export const parseWsAuth = (content: string): WsAuthParseResult => {+ const routes: WsAuthRoute[] = [];+ const errors: WsAuthParseError[] = [];+ const json = parseJson(content, errors);+ if (json === undefined) {+ return { routes, errors };+ }+ if (isRecord(json) === false) {+ errors.push({ path: "$", message: "Auth config must be an object" });+ return { routes, errors };+ }+ if (json.version !== 1) {+ errors.push({ path: "version", message: "Version must be 1" });+ }+ if (isRecord(json.routes) === false) {+ errors.push({ path: "routes", message: "Routes must be an object" });+ return { routes, errors };+ }++ for (const [route, authInput] of Object.entries(json.routes)) {+ const routeError = validateWsAuthRoute(route);+ if (routeError) {+ errors.push({+ path: `routes.${JSON.stringify(route)}`,+ message: routeError,+ });+ continue;+ }+ if (isRecord(authInput) === false) {+ errors.push({+ path: `routes.${JSON.stringify(route)}`,+ message: "Auth rule must be an object",+ });+ continue;+ }+ if (authInput.method !== "basic") {+ errors.push({+ path: `routes.${JSON.stringify(route)}.method`,+ message: 'Auth method must be "basic"',+ });+ continue;+ }+ const login = authInput.login;+ const password = authInput.password;+ if (typeof login !== "string") {+ errors.push({+ path: `routes.${JSON.stringify(route)}.login`,+ message: "Login must be a string",+ });+ continue;+ }+ if (typeof password !== "string") {+ errors.push({+ path: `routes.${JSON.stringify(route)}.password`,+ message: "Password must be a string",+ });+ continue;+ }+ const validation = validateBasicAuth({ login, password });+ if (validation.auth === undefined) {+ for (const issue of validation.issues ?? []) {+ errors.push({+ path: `routes.${JSON.stringify(route)}.${issue.path[0]}`,+ message: issue.message,+ });+ }+ continue;+ }+ const auth = validation.auth;+ routes.push({ route, auth });+ }+ return { routes, errors };+};++export const parseWsAuthOrThrow = (+ content: string,+ sourceName: string+): WsAuthRoute[] => {+ const result = parseWsAuth(content);+ if (result.errors.length > 0) {+ const message = result.errors+ .map((error) => `${sourceName}:${error.path} ${error.message}`)+ .join("\n");+ throw new Error(message);+ }+ return result.routes;+};++export const serializeWsAuth = (routes: WsAuthRoute[]) => {+ const config: WsAuthConfig = { version: 1, routes: {} };+ for (const { route, auth } of routes) {+ switch (auth.method) {+ case "basic":+ config.routes[route] = {+ method: "basic",+ login: auth.login,+ password: auth.password,+ };+ break;+ }+ }+ return `${JSON.stringify(config, null, 2)}\n`;+};++const collectWsAuthRoutes = (sources: WsAuthSource[]) => {+ return sources.flatMap((source) => {+ if ("content" in source) {+ return parseWsAuthOrThrow(source.content, source.name);+ }+ return source.routes;+ });+};++export const buildWsAuth = (sources: WsAuthSource[]): WsAuthBuildResult => {+ const content = serializeWsAuth(collectWsAuthRoutes(sources));+ const routes = parseWsAuthOrThrow(content, "Serialized auth config");+ return {+ routes,+ content,+ };+};++export const createWsAuthResources = ({+ projectContent = "",+ pages,+ projectSourceName = "Auth",+ generatedSourceName = "Generated page auth",+}: WsAuthResourcesInput): WsAuthResources => {+ const generatedRoutes = pages.flatMap((page) => {+ const route = createWsAuthRouteFromPage(page);+ return route === undefined ? [] : [route];+ });+ const result = buildWsAuth([+ { name: projectSourceName, content: projectContent },+ { name: generatedSourceName, routes: generatedRoutes },+ ]);+ console.info("[wsauth] create resources", {+ projectContentLength: projectContent.length,+ projectContent,+ pageCount: pages.length,+ pages,+ generatedRouteCount: generatedRoutes.length,+ generatedRoutes,+ routeCount: result.routes.length,+ routes: result.routes,+ });+ return {+ ...result,+ module: [+ `import type { WsAuthRoute } from "@webstudio-is/wsauth";`,+ "",+ `export const authRoutes: WsAuthRoute[] = ${JSON.stringify(+ result.routes,+ null,+ 2+ )};`,+ "",+ ].join("\n"),+ };+};++const decodeBase64 = (value: string) => {+ try {+ if (typeof atob === "function") {+ return atob(value);+ }+ const buffer = (+ globalThis as {+ Buffer?: {+ from: (+ value: string,+ encoding: "base64"+ ) => { toString: (encoding: "utf-8") => string };+ };+ }+ ).Buffer;+ return buffer?.from(value, "base64").toString("utf-8") ?? "";+ } catch {+ return "";+ }+};++export const getBasicAuthCredentials = (authorization: string | null) => {+ const [scheme, encodedCredentials] = authorization?.split(/\s+/, 2) ?? [];+ const credentials =+ scheme?.toLowerCase() === "basic" && encodedCredentials !== undefined+ ? decodeBase64(encodedCredentials)+ : "";+ const auth = parseBasicAuthExpression(credentials);+ return auth?.credentials;+};++const normalizePathname = (pathname: string) => {+ if (pathname === "" || pathname === "/") {+ return "/";+ }+ return pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;+};++export const matchWsAuthRoute = (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))+ );+ }+ if (pathnameSegment === undefined) {+ return false;+ }+ if (/^:\w+$/.test(routeSegment)) {+ return matchSegments(routeIndex + 1, pathnameIndex + 1);+ }+ return (+ routeSegment === pathnameSegment &&+ matchSegments(routeIndex + 1, pathnameIndex + 1)+ );+ };+ return matchSegments(0, 0);+};++export const findWsAuthRoute = (+ authRoutes: WsAuthRoute[],+ pathname: string+) => {+ const authRoute = authRoutes.find(({ route }) =>+ matchWsAuthRoute(route, pathname)+ );+ console.info("[wsauth] find route", {+ pathname,+ routeCount: authRoutes.length,+ authRoutes,+ matchedRoute: authRoute?.route,+ matchedAuth: authRoute?.auth,+ });+ return authRoute;+};++export const authenticateRequest = (+ request: Request,+ authRoutes: WsAuthRoute[]+) => {+ const url = new URL(request.url);+ const authorization = request.headers.get("Authorization");+ console.info("[wsauth] authenticate request", {+ method: request.method,+ url: url.href,+ pathname: url.pathname,+ routeCount: authRoutes.length,+ authRoutes,+ hasAuthorization: authorization !== null,+ authorization,+ authorizationScheme: authorization?.split(/\s+/, 1)[0]?.toLowerCase(),+ });+ const authRoute = findWsAuthRoute(authRoutes, url.pathname);+ if (authRoute === undefined) {+ console.info("[wsauth] authenticate result", {+ pathname: url.pathname,+ result: "not-protected",+ });+ return;+ }+ if (authRoute.auth.method === "basic") {+ const credentials = getBasicAuthCredentials(authorization);+ if (credentials === authRoute.auth.credentials) {+ console.info("[wsauth] authenticate result", {+ pathname: url.pathname,+ route: authRoute.route,+ method: authRoute.auth.method,+ result: "authorized",+ hasParsedCredentials: credentials !== undefined,+ parsedCredentials: credentials,+ expectedCredentials: authRoute.auth.credentials,+ expectedLogin: authRoute.auth.login,+ expectedPassword: authRoute.auth.password,+ });+ return authRoute;+ }+ console.warn("[wsauth] authenticate result", {+ pathname: url.pathname,+ route: authRoute.route,+ method: authRoute.auth.method,+ result: "unauthorized",+ hasAuthorization: authorization !== null,+ hasParsedCredentials: credentials !== undefined,+ authorization,+ parsedCredentials: credentials,+ expectedCredentials: authRoute.auth.credentials,+ expectedLogin: authRoute.auth.login,+ expectedPassword: authRoute.auth.password,+ });+ throw new Response("Authentication required", {+ status: 401,+ headers: {+ "WWW-Authenticate": `Basic realm="Webstudio"`,+ "Cache-Control": "private, no-store",+ },+ });+ }+};diff --git a/packages/wsauth/tsconfig.dts.json b/packages/wsauth/tsconfig.dts.jsonnew file mode 100644index 0000000000..72bd162f74--- /dev/null+++ b/packages/wsauth/tsconfig.dts.json@@ -0,0 +1,9 @@+{+ "extends": "@webstudio-is/tsconfig/base.json",+ "include": ["src"],+ "compilerOptions": {+ "emitDeclarationOnly": true,+ "declaration": true,+ "outDir": "lib/types"+ }+}diff --git a/packages/wsauth/tsconfig.json b/packages/wsauth/tsconfig.jsonnew file mode 100644index 0000000000..d2e5040f8f--- /dev/null+++ b/packages/wsauth/tsconfig.json@@ -0,0 +1,3 @@+{+ "extends": "@webstudio-is/tsconfig/base.json"+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 472a923ccf..9851b8a396 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -295,6 +295,9 @@ importers:'@webstudio-is/trpc-interface':specifier: workspace:*version: link:../../packages/trpc-interface+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthargs-tokenizer:specifier: ^0.3.0version: 0.3.0@@ -515,6 +518,9 @@ importers:'@webstudio-is/sdk-components-react-router':specifier: workspace:*version: link:../../packages/sdk-components-react-router+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthisbot:specifier: ^5.1.25version: 5.1.25@@ -582,6 +588,9 @@ importers:'@webstudio-is/sdk-components-react-router':specifier: workspace:*version: link:../../packages/sdk-components-react-router+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthh3:specifier: ^1.15.1version: 1.15.1@@ -652,6 +661,9 @@ importers:'@webstudio-is/sdk-components-react-router':specifier: workspace:*version: link:../../packages/sdk-components-react-router+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthisbot:specifier: ^5.1.25version: 5.1.25@@ -716,6 +728,9 @@ importers:'@webstudio-is/sdk-components-react-router':specifier: workspace:*version: link:../../packages/sdk-components-react-router+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthisbot:specifier: ^5.1.25version: 5.1.25@@ -768,6 +783,9 @@ importers:'@webstudio-is/sdk-components-react-remix':specifier: workspace:*version: link:../../packages/sdk-components-react-remix+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthreact:specifier: 18.3.0-canary-14898b6a9-20240318version: 18.3.0-canary-14898b6a9-20240318@@ -823,6 +841,9 @@ importers:'@webstudio-is/sdk-components-react-remix':specifier: workspace:*version: link:../../packages/sdk-components-react-remix+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthreact:specifier: 18.3.0-canary-14898b6a9-20240318version: 18.3.0-canary-14898b6a9-20240318@@ -893,6 +914,9 @@ importers:'@webstudio-is/sdk-components-react-remix':specifier: workspace:*version: link:../../packages/sdk-components-react-remix+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthisbot:specifier: ^5.1.25version: 5.1.25@@ -972,6 +996,9 @@ importers:'@webstudio-is/sdk-components-react-router':specifier: workspace:*version: link:../../packages/sdk-components-react-router+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../../packages/wsauthisbot:specifier: ^5.1.25version: 5.1.25@@ -1219,6 +1246,9 @@ importers:'@webstudio-is/tsconfig':specifier: workspace:*version: link:../tsconfig+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../wsauthh3:specifier: ^1.15.1version: 1.15.1@@ -1978,6 +2008,9 @@ importers:'@webstudio-is/icons':specifier: workspace:*version: link:../icons+ '@webstudio-is/wsauth':+ specifier: workspace:*+ version: link:../wsauthacorn:specifier: ^8.14.1version: 8.14.1@@ -2414,6 +2447,15 @@ importers:packages/tsconfig: {}+ packages/wsauth:+ devDependencies:+ '@webstudio-is/tsconfig':+ specifier: workspace:*+ version: link:../tsconfig+ vitest:+ specifier: ^3.1.2+ version: 3.1.2(@types/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+packages:'@ampproject/[email protected]':