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: configure custom response headers by route (#6429)
Oleg Isonen2c9fd16689c1
diff --git a/apps/builder/app/builder/features/publish/restricted-features.test.ts b/apps/builder/app/builder/features/publish/restricted-features.test.tsindex 32222e91b6..f788ab4292 100644--- a/apps/builder/app/builder/features/publish/restricted-features.test.ts+++ b/apps/builder/app/builder/features/publish/restricted-features.test.ts@@ -128,6 +128,79 @@ const getPageRestrictedFeatures = (isDraft: boolean) => {};describe("getRestrictedFeatures", () => {+ test("restricts customized headers on the free plan", () => {+ const features = getFeatures({+ pages: createPages(),+ projectSettings: {+ compiler: {},+ meta: { customHeaders: [{ name: "X-Frame-Options", value: "DENY" }] },+ },+ permissions: { allowDynamicData: false },+ });++ expect([...features.keys()]).toEqual(["Custom headers"]);+ });++ test("restricts path-specific header rules on the free plan", () => {+ const features = getFeatures({+ pages: createPages(),+ projectSettings: {+ compiler: {},+ meta: {+ customHeaders: [+ {+ route: "/private/*",+ name: "Referrer-Policy",+ value: "no-referrer",+ },+ ],+ },+ },+ permissions: { allowDynamicData: false },+ });+ expect(features.has("Custom headers")).toBe(true);+ });++ test("allows custom headers on the Pro plan", () => {+ const features = getFeatures({+ pages: createPages(),+ projectSettings: {+ compiler: {},+ meta: {+ customHeaders: [+ {+ name: "Content-Security-Policy",+ value: "frame-ancestors https://example.com",+ },+ { name: "X-Frame-Options", value: null },+ ],+ },+ },+ permissions: { allowDynamicData: true },+ });++ expect(features.has("Custom headers")).toBe(false);+ });++ test.each([+ undefined,+ [],+ [{ name: "X-Frame-Options", value: null }],+ [{ name: "Content-Security-Policy", value: "frame-ancestors 'self'" }],+ [{ name: "x-frame-options", value: "SAMEORIGIN" }],+ ])(+ "does not warn about missing or deleted custom headers (%j)",+ (customHeaders) => {+ const features = getFeatures({+ pages: createPages(),+ projectSettings: { compiler: {}, meta: { customHeaders } },+ permissions: { allowDynamicData: false },+ });++ expect(features.has("Custom headers")).toBe(false);+ }+ );+test("restricts project authentication when auth is not allowed", () => {const features = getFeatures({pages: createPages(),diff --git a/apps/builder/app/builder/features/publish/restricted-features.ts b/apps/builder/app/builder/features/publish/restricted-features.tsindex 3b73a28794..8d5241b64e 100644--- a/apps/builder/app/builder/features/publish/restricted-features.ts+++ b/apps/builder/app/builder/features/publish/restricted-features.ts@@ -1,6 +1,7 @@import type { ReactNode } from "react";import {getPublishablePages,+ hasCustomResponseHeaders,isAssetsResource,isPathnamePattern,type DataSource,@@ -70,6 +71,11 @@ export const getRestrictedFeatures = ({}}if (permissions.allowDynamicData === false) {+ // Headers share the Pro publishing entitlement used by dynamic pages and+ // resources. Only changes from the defaults require it.+ if (hasCustomResponseHeaders(projectMeta?.customHeaders)) {+ features.set("Custom headers", undefined);+ }for (const page of publishablePages) {const navigate = {pageId: page.id,diff --git a/apps/builder/app/shared/nano-states/project-settings.ts b/apps/builder/app/shared/nano-states/project-settings.tsindex fd499fb65b..8c7872548e 100644--- a/apps/builder/app/shared/nano-states/project-settings.ts+++ b/apps/builder/app/shared/nano-states/project-settings.ts@@ -4,6 +4,7 @@ export type SectionName =| "general"| "agents"| "auth"+ | "headers"| "redirects"| "publish"| "marketplace"diff --git a/apps/builder/app/shared/project-settings/data-row.tsx b/apps/builder/app/shared/project-settings/data-row.tsxindex ecfce5f9c6..82d3658137 100644--- a/apps/builder/app/shared/project-settings/data-row.tsx+++ b/apps/builder/app/shared/project-settings/data-row.tsx@@ -1,20 +1,19 @@-import { Grid, cssVar, styled, theme } from "@webstudio-is/design-system";+import { Grid, styled, theme } from "@webstudio-is/design-system";export const ProjectSettingsDataRow = styled(Grid, {p: theme.spacing[3],overflow: "hidden",position: "relative",- "& > button": {+ "& > button, & > [role='cell'] > button": {opacity: 0,position: "absolute",- right: 0,- top: 0,- bottom: 0,- height: "auto",- borderRadius: 0,- background: cssVar("--background-primary"),+ right: theme.spacing[2],+ top: "50%",+ transform: "translateY(-50%)",},- "&:hover > button, &:focus-within > button": {- opacity: 1,+ "&:hover, &:focus-within": {+ "& > button, & > [role='cell'] > button": {+ opacity: 1,+ },},});diff --git a/apps/builder/app/shared/project-settings/project-settings.stories.tsx b/apps/builder/app/shared/project-settings/project-settings.stories.tsxindex c4e23e40c4..36bf9e98fb 100644--- a/apps/builder/app/shared/project-settings/project-settings.stories.tsx+++ b/apps/builder/app/shared/project-settings/project-settings.stories.tsx@@ -1,9 +1,10 @@-import type { JSX } from "react";+import { useEffect, type JSX } from "react";import { createBrowserRouter, RouterProvider } from "react-router-dom";import { StorySection } from "@webstudio-is/design-system";import { ProjectSettingsDialog } from "./project-settings";-import { $pages, $project } from "~/shared/sync/data-stores";+import { $pages, $project, $projectSettings } from "~/shared/sync/data-stores";import type { Project } from "@webstudio-is/project";+import { $authPermit, $builderMode } from "~/shared/nano-states";export default {title: "Project settings",@@ -32,6 +33,52 @@ export const General = () => {);};+const HeadersStory = ({ customized = false }: { customized?: boolean }) => {+ useEffect(() => {+ const previousSettings = $projectSettings.get();+ const previousPermit = $authPermit.get();+ const previousMode = $builderMode.get();+ $authPermit.set("own");+ $builderMode.set("design");+ $projectSettings.set({+ meta: customized+ ? {+ customHeaders: [+ {+ name: "Content-Security-Policy",+ value:+ "frame-ancestors 'self' https://example.com https://another-example.com",+ },+ { name: "X-Frame-Options", value: null },+ {+ route: "/private/*",+ name: "Referrer-Policy",+ value: "no-referrer",+ },+ ],+ }+ : {},+ compiler: {},+ });+ return () => {+ $projectSettings.set(previousSettings);+ $authPermit.set(previousPermit);+ $builderMode.set(previousMode);+ };+ }, [customized]);+ const router = createRouter(+ <ProjectSettingsDialog currentSection="headers" />+ );+ return (+ <StorySection title="Headers">+ <RouterProvider router={router} />+ </StorySection>+ );+};++export const Headers = () => <HeadersStory customized />;+export const HeadersDefaults = () => <HeadersStory />;+export const Redirects = () => {$pages.set({homePageId: "pageId",diff --git a/apps/builder/app/shared/project-settings/project-settings.tsx b/apps/builder/app/shared/project-settings/project-settings.tsxindex 1e552e1732..4172b248c4 100644--- a/apps/builder/app/shared/project-settings/project-settings.tsx+++ b/apps/builder/app/shared/project-settings/project-settings.tsx@@ -26,6 +26,7 @@ import { leftPanelWidth, rightPanelWidth } from "./utils";import { SectionGeneral } from "./section-general";import { SectionAgents } from "./section-agents";import { SectionAuth } from "./section-auth";+import { SectionHeaders } from "./section-headers";import { SectionRedirects } from "./section-redirects";import { SectionPublish } from "./section-publish";import { SectionMarketplace } from "./section-marketplace";@@ -43,6 +44,7 @@ const sections = new Map<["marketplace", SectionMarketplace],["backups", SectionBackups],["auth", SectionAuth],+ ["headers", SectionHeaders],] as const);const sectionLabels = new Map<SectionName, string>([diff --git a/apps/builder/app/shared/project-settings/response-header-suggestions.test.ts b/apps/builder/app/shared/project-settings/response-header-suggestions.test.tsnew file mode 100644index 0000000000..253d98f588--- /dev/null+++ b/apps/builder/app/shared/project-settings/response-header-suggestions.test.ts@@ -0,0 +1,49 @@+import { expect, test } from "vitest";+import { forbiddenCustomResponseHeaderNames } from "@webstudio-is/sdk";+import {+ getResponseHeaderName,+ getResponseHeaderValueSuggestions,+ responseHeaderNames,+} from "./response-header-suggestions";++test("suggests response headers but excludes platform-owned names", () => {+ expect(responseHeaderNames).toContain("Content-Security-Policy");+ expect(responseHeaderNames).toContain("Access-Control-Allow-Origin");+ expect(responseHeaderNames).toContain(+ "Cross-Origin-Embedder-Policy-Report-Only"+ );+ expect(responseHeaderNames).toContain(+ "Cross-Origin-Opener-Policy-Report-Only"+ );+ expect(responseHeaderNames).not.toContain("Set-Cookie");+ for (const name of forbiddenCustomResponseHeaderNames) {+ expect(+ responseHeaderNames.some(+ (suggestion) => suggestion.toLowerCase() === name+ )+ ).toBe(false);+ }+ expect(responseHeaderNames).not.toContain("X-Powered-By");+ expect(responseHeaderNames).not.toContain("X-Content-Type-Options");+ expect(responseHeaderNames).not.toContain("Strict-Transport-Security");+ expect(getResponseHeaderName("referrer-policy")).toBe("Referrer-Policy");+ expect(getResponseHeaderName("X-Custom-Header")).toBeUndefined();+});++test("suggests values for the selected header without restricting custom values", () => {+ expect(getResponseHeaderValueSuggestions(" cache-control ")).toContain(+ "no-store"+ );+ expect(getResponseHeaderValueSuggestions("cache-control")).not.toContain(+ "SAMEORIGIN"+ );+ expect(getResponseHeaderValueSuggestions("x-frame-options")).toContain(+ "SAMEORIGIN"+ );+ expect(+ getResponseHeaderValueSuggestions(+ "Cross-Origin-Embedder-Policy-Report-Only"+ )+ ).toContain("require-corp");+ expect(getResponseHeaderValueSuggestions("X-Custom-Header")).toEqual([]);+});diff --git a/apps/builder/app/shared/project-settings/response-header-suggestions.ts b/apps/builder/app/shared/project-settings/response-header-suggestions.tsnew file mode 100644index 0000000000..d6c0c4b30c--- /dev/null+++ b/apps/builder/app/shared/project-settings/response-header-suggestions.ts@@ -0,0 +1,139 @@+// Response fields that are useful on published sites. Platform-owned fields are+// deliberately excluded. Names are suggestions, not an allowlist; the shared+// response-header schema rejects forbidden customizations even when typed manually.+export const responseHeaderNames = [+ "Accept-CH",+ "Accept-Patch",+ "Accept-Post",+ "Accept-Ranges",+ "Access-Control-Allow-Credentials",+ "Access-Control-Allow-Headers",+ "Access-Control-Allow-Methods",+ "Access-Control-Allow-Origin",+ "Access-Control-Expose-Headers",+ "Access-Control-Max-Age",+ "Age",+ "Allow",+ "Alt-Svc",+ "Cache-Control",+ "Cache-Status",+ "CDN-Cache-Control",+ "Clear-Site-Data",+ "Content-Disposition",+ "Content-Digest",+ "Content-Language",+ "Content-Location",+ "Content-Security-Policy",+ "Content-Security-Policy-Report-Only",+ "Content-Type",+ "Cross-Origin-Embedder-Policy",+ "Cross-Origin-Embedder-Policy-Report-Only",+ "Cross-Origin-Opener-Policy",+ "Cross-Origin-Opener-Policy-Report-Only",+ "Cross-Origin-Resource-Policy",+ "Critical-CH",+ "ETag",+ "Expires",+ "Last-Modified",+ "Link",+ "Location",+ "NEL",+ "Origin-Agent-Cluster",+ "Permissions-Policy",+ "Priority",+ "Proxy-Status",+ "Referrer-Policy",+ "Reporting-Endpoints",+ "Repr-Digest",+ "Retry-After",+ "Server",+ "Server-Timing",+ "Service-Worker-Allowed",+ "SourceMap",+ "Speculation-Rules",+ "Supports-Loading-Mode",+ "Timing-Allow-Origin",+ "Vary",+ "WWW-Authenticate",+ "X-Frame-Options",+] as const;++const responseHeaderValues: Record<string, readonly string[]> = {+ "accept-ranges": ["bytes", "none"],+ "access-control-allow-credentials": ["true"],+ "access-control-allow-headers": ["Content-Type", "Authorization"],+ "access-control-allow-methods": [+ "GET, HEAD, POST",+ "GET, POST, PUT, DELETE, OPTIONS",+ ],+ "access-control-allow-origin": ["*"],+ "access-control-expose-headers": ["Content-Disposition", "ETag"],+ "access-control-max-age": ["600", "86400"],+ "cache-control": [+ "no-store",+ "no-cache",+ "private, no-store",+ "public, max-age=3600",+ "public, max-age=31536000, immutable",+ ],+ "cdn-cache-control": ["no-store", "public, max-age=3600"],+ "clear-site-data": ['"cache"', '"cookies"', '"storage"', '"*"'],+ "content-disposition": ["inline", "attachment"],+ "content-security-policy": [+ "frame-ancestors 'self'",+ "frame-ancestors 'none'",+ "default-src 'self'",+ ],+ "content-security-policy-report-only": ["default-src 'self'"],+ "content-type": [+ "text/html; charset=utf-8",+ "text/plain; charset=utf-8",+ "application/json",+ "application/xml",+ ],+ "cross-origin-embedder-policy": [+ "unsafe-none",+ "require-corp",+ "credentialless",+ ],+ "cross-origin-embedder-policy-report-only": [+ "require-corp",+ "credentialless",+ ],+ "cross-origin-opener-policy": [+ "unsafe-none",+ "same-origin",+ "same-origin-allow-popups",+ "noopener-allow-popups",+ ],+ "cross-origin-opener-policy-report-only": [+ "same-origin",+ "same-origin-allow-popups",+ ],+ "cross-origin-resource-policy": ["same-origin", "same-site", "cross-origin"],+ "origin-agent-cluster": ["?1", "?0"],+ "permissions-policy": ["geolocation=()", "camera=()", "microphone=()"],+ "referrer-policy": [+ "strict-origin-when-cross-origin",+ "no-referrer",+ "no-referrer-when-downgrade",+ "origin",+ "origin-when-cross-origin",+ "same-origin",+ "strict-origin",+ "unsafe-url",+ ],+ "service-worker-allowed": ["/"],+ "supports-loading-mode": ["credentialed-prerender"],+ "timing-allow-origin": ["*"],+ vary: ["Accept-Encoding", "Origin", "*"],+ "x-frame-options": ["SAMEORIGIN", "DENY"],+};++export const getResponseHeaderName = (name: string) =>+ responseHeaderNames.find(+ (standardName) => standardName.toLowerCase() === name.toLowerCase()+ );++export const getResponseHeaderValueSuggestions = (name: string) =>+ responseHeaderValues[name.trim().toLowerCase()] ?? [];diff --git a/apps/builder/app/shared/project-settings/rule-list.test.tsx b/apps/builder/app/shared/project-settings/rule-list.test.tsxnew file mode 100644index 0000000000..32eb8b364e--- /dev/null+++ b/apps/builder/app/shared/project-settings/rule-list.test.tsx@@ -0,0 +1,187 @@+import { createRoot } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { expect, test, vi } from "vitest";+import { userEvent } from "@vitest/browser/context";+import { SmallIconButton, TooltipProvider } from "@webstudio-is/design-system";+import {+ ProjectSettingsDeleteRuleButton,+ ProjectSettingsRuleList,+} from "./rule-list";++test("invalid route disables Add until corrected", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const onSubmit = vi.fn(() => true);+ act(() => {+ root.render(+ <TooltipProvider>+ <ProjectSettingsRuleList+ fields={[+ {+ name: "route",+ placeholder: "Route",+ suggestions: [],+ validateOnChange: (value) =>+ value.startsWith("/") ? [] : ["Route must start with /"],+ },+ ]}+ validate={(values) => ({+ route: values.route?.startsWith("/")+ ? []+ : ["Route must start with /"],+ })}+ onSubmit={onSubmit}+ rules={[]}+ columns="1fr"+ columnLabels={["Path"]}+ label="Rules"+ />+ </TooltipProvider>+ );+ });+ const input = container.querySelector<HTMLInputElement>("input");+ const add = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent === "Add"+ );+ if (!input || !add) {+ throw new Error("Expected the rule form");+ }+ const type = (value: string) => {+ act(() => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set?.call(input, value);+ input.dispatchEvent(new InputEvent("input", { bubbles: true }));+ });+ };+ type("private");+ expect(add.disabled).toBe(true);+ expect(onSubmit).not.toHaveBeenCalled();+ type("/private");+ expect(add.disabled).toBe(false);+ act(() => add.click());+ expect(onSubmit).toHaveBeenCalledWith({ route: "/private" });+ act(() => root.unmount());+ container.remove();+});++test("rules expose table cells and support keyboard navigation to actions", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const onRemove = vi.fn();+ act(() => {+ root.render(+ <TooltipProvider>+ <ProjectSettingsRuleList+ fields={[]}+ validate={() => ({})}+ onSubmit={() => true}+ label="Response header rules"+ columnLabels={["Path", "Header"]}+ columns="1fr 1fr"+ rules={[+ {+ key: "one",+ values: ["/*", "Content-Security-Policy"],+ },+ {+ key: "two",+ values: ["/private", "X-Frame-Options"],+ actions: (+ <SmallIconButton+ icon={<span>Remove</span>}+ aria-label="Remove X-Frame-Options"+ onClick={onRemove}+ />+ ),+ },+ ]}+ />+ </TooltipProvider>+ );+ });+ const table = container.querySelector('[role="table"]');+ const rows = Array.from(+ container.querySelectorAll<HTMLElement>('[role="row"]')+ );+ expect(table?.getAttribute("aria-label")).toBe("Response header rules");+ expect(container.querySelectorAll('[role="columnheader"]')).toHaveLength(3);+ expect(rows).toHaveLength(3);+ expect(rows[1]?.querySelectorAll('[role="cell"]')).toHaveLength(3);+ expect(rows[1]?.tabIndex).toBe(0);+ expect(rows[2]?.tabIndex).toBe(-1);+ const removeButton = rows[2]?.querySelector("button");+ expect(removeButton && getComputedStyle(removeButton).opacity).toBe("0");+ act(() => {+ rows[1]?.focus();+ rows[1]?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })+ );+ });+ expect(document.activeElement).toBe(rows[2]);+ expect(removeButton && getComputedStyle(removeButton).opacity).toBe("1");+ expect(rows[2]?.querySelector("button")?.getAttribute("aria-label")).toBe(+ "Remove X-Frame-Options"+ );+ removeButton?.focus();+ await act(async () => userEvent.keyboard("{Enter}"));+ expect(onRemove).toHaveBeenCalledOnce();+ removeButton?.focus();+ await act(async () => userEvent.keyboard("{Space}"));+ expect(onRemove).toHaveBeenCalledTimes(2);+ act(() => root.unmount());+ container.remove();+});++test("rule deletion requires confirmation", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const onDelete = vi.fn();+ act(() => {+ root.render(+ <TooltipProvider>+ <ProjectSettingsDeleteRuleButton+ label="Remove Cache-Control"+ description="Cache-Control for /*"+ onDelete={onDelete}+ />+ </TooltipProvider>+ );+ });+ const deleteButton = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Remove Cache-Control"]'+ );+ if (!deleteButton) {+ throw new Error("Expected a delete button");+ }+ await act(async () => userEvent.click(deleteButton));+ expect(onDelete).not.toHaveBeenCalled();+ expect(document.body.textContent).toContain("delete Cache-Control for /*?");+ expect(document.body.textContent).not.toContain("cannot be undone");+ const cancelButton = Array.from(+ document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')+ ).find((button) => button.textContent === "Cancel");+ if (!cancelButton) {+ throw new Error("Expected a cancel button");+ }+ await act(async () => userEvent.click(cancelButton));+ expect(onDelete).not.toHaveBeenCalled();+ await vi.waitFor(() => {+ expect(document.querySelector('[role="dialog"]')).toBeNull();+ });+ await act(async () => userEvent.click(deleteButton));+ const confirmButton = Array.from(+ document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')+ ).find((button) => button.textContent === "Delete");+ if (!confirmButton) {+ throw new Error("Expected a confirmation button");+ }+ await act(async () => userEvent.click(confirmButton));+ expect(onDelete).toHaveBeenCalledOnce();+ act(() => root.unmount());+ container.remove();+});diff --git a/apps/builder/app/shared/project-settings/rule-list.tsx b/apps/builder/app/shared/project-settings/rule-list.tsxnew file mode 100644index 0000000000..939dfe7b27--- /dev/null+++ b/apps/builder/app/shared/project-settings/rule-list.tsx@@ -0,0 +1,292 @@+import { useRef, useState, type ReactNode } from "react";+import {+ Button,+ Combobox,+ Dialog,+ DialogActions,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogTitle,+ Flex,+ Grid,+ InputErrorsTooltip,+ InputField,+ InsetList,+ InsetListItem,+ List,+ ListItem,+ PanelContent,+ ScrollArea,+ SmallIconButton,+ Text,+ theme,+} from "@webstudio-is/design-system";+import { TrashIcon } from "@webstudio-is/icons";+import { ProjectSettingsDataRow } from "./data-row";++type Values = Record<string, string>;+type Errors = Record<string, string[]>;++type Field = {+ name: string;+ placeholder: string;+ type?: "text" | "password";+ suggestions?: readonly string[] | ((values: Values) => readonly string[]);+ validateOnChange?: (value: string) => string[];+};++type Rule = {+ key: string;+ values: ReactNode[];+ actions?: ReactNode;+};++export const ProjectSettingsDeleteRuleButton = ({+ label,+ description,+ onDelete,+}: {+ label: string;+ description: string;+ onDelete: () => void;+}) => {+ const [open, setOpen] = useState(false);+ const buttonRef = useRef<HTMLButtonElement>(null);++ return (+ <>+ <SmallIconButton+ ref={buttonRef}+ variant="destructive"+ icon={<TrashIcon />}+ aria-label={label}+ onClick={() => setOpen(true)}+ />+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent+ onCloseAutoFocus={(event) => {+ if (buttonRef.current?.isConnected) {+ event.preventDefault();+ buttonRef.current.focus();+ }+ }}+ >+ <DialogTitle>Delete rule</DialogTitle>+ <DialogDescription asChild>+ <PanelContent as={Flex}>+ <Text>Are you sure you want to delete {description}?</Text>+ </PanelContent>+ </DialogDescription>+ <DialogActions>+ <Button+ color="destructive"+ onClick={() => {+ onDelete();+ setOpen(false);+ }}+ >+ Delete+ </Button>+ <DialogClose>+ <Button color="ghost" autoFocus>+ Cancel+ </Button>+ </DialogClose>+ </DialogActions>+ </DialogContent>+ </Dialog>+ </>+ );+};++export const ProjectSettingsRuleList = ({+ fields,+ validate,+ onSubmit,+ rules,+ columns,+ columnLabels,+ label,+}: {+ fields: Field[];+ validate: (values: Values) => Errors;+ onSubmit: (values: Values) => boolean;+ rules: Rule[];+ columns: string;+ columnLabels: string[];+ label: string;+}) => {+ const [values, setValues] = useState<Values>({});+ const [errors, setErrors] = useState<Errors>({});+ const [formRevision, setFormRevision] = useState(0);+ const firstInputRef = useRef<HTMLInputElement>(null);++ const submit = () => {+ const nextErrors = validate(values);+ setErrors(nextErrors);+ if (Object.values(nextErrors).some((messages) => messages.length > 0)) {+ setFormRevision((current) => current + 1);+ return;+ }+ if (onSubmit(values)) {+ setValues({});+ setErrors({});+ firstInputRef.current?.focus();+ } else {+ // Downshift clears an unselected free-form value on blur. Remount the+ // comboboxes after a failed save to restore the values kept in state.+ setFormRevision((current) => current + 1);+ }+ };++ return (+ <>+ <Flex gap="2" align="center">+ {fields.map((field, index) => (+ <Flex key={field.name} grow css={{ minWidth: 0 }}>+ <InputErrorsTooltip+ errors={+ errors[field.name]?.length ? errors[field.name] : undefined+ }+ side="top"+ >+ {field.suggestions ? (+ <Combobox<string>+ key={formRevision}+ modal={false}+ inputRef={index === 0 ? firstInputRef : undefined}+ autoFocus={index === 0}+ placeholder={field.placeholder}+ value={values[field.name] ?? ""}+ color={errors[field.name]?.length ? "error" : undefined}+ getItems={() => [+ ...(typeof field.suggestions === "function"+ ? field.suggestions(values)+ : (field.suggestions ?? [])),+ ]}+ itemToString={(item) => item ?? ""}+ onItemSelect={(value) => {+ setValues((current) => ({+ ...current,+ [field.name]: value ?? "",+ }));+ setFormRevision((current) => current + 1);+ setErrors((current) => ({+ ...current,+ [field.name]: field.validateOnChange?.(value ?? "") ?? [],+ }));+ }}+ onChange={(value) => {+ if (value !== undefined) {+ setValues((current) => ({+ ...current,+ [field.name]: value,+ }));+ setErrors((current) => ({+ ...current,+ [field.name]: field.validateOnChange?.(value) ?? [],+ }));+ }+ }}+ />+ ) : (+ <InputField+ placeholder={field.placeholder}+ type={field.type}+ value={values[field.name] ?? ""}+ color={errors[field.name]?.length ? "error" : undefined}+ onChange={(event) => {+ setValues((current) => ({+ ...current,+ [field.name]: event.target.value,+ }));+ setErrors((current) => ({+ ...current,+ [field.name]:+ field.validateOnChange?.(event.target.value) ?? [],+ }));+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ submit();+ }+ }}+ />+ )}+ </InputErrorsTooltip>+ </Flex>+ ))}+ <Button+ color="primary"+ disabled={Object.values(errors).some(+ (messages) => messages.length > 0+ )}+ onClick={submit}+ css={{ flexShrink: 0 }}+ >+ Add+ </Button>+ </Flex>+ {rules.length > 0 && (+ <ScrollArea>+ <Grid role="table" aria-label={label}>+ <Grid role="rowgroup">+ <Grid+ role="row"+ gap="2"+ css={{+ gridTemplateColumns: `${columns} ${theme.spacing[9]}`,+ p: theme.spacing[3],+ }}+ >+ {columnLabels.map((columnLabel) => (+ <Text+ key={columnLabel}+ role="columnheader"+ variant="regularBold"+ >+ {columnLabel}+ </Text>+ ))}+ <Text role="columnheader" aria-label="Actions" />+ </Grid>+ </Grid>+ <List asChild>+ <InsetList role="rowgroup">+ {rules.map(({ key, values, actions }, index) => (+ <ListItem asChild key={key} index={index}>+ <InsetListItem asChild>+ <ProjectSettingsDataRow+ role="row"+ align="center"+ gap="2"+ css={{+ gridTemplateColumns: `${columns} ${theme.spacing[9]}`,+ }}+ >+ {values.map((value, index) => (+ <Flex key={index} role="cell" css={{ minWidth: 0 }}>+ {value}+ </Flex>+ ))}+ <Flex+ role="cell"+ align="center"+ onKeyDown={(event) => event.stopPropagation()}+ >+ {actions}+ </Flex>+ </ProjectSettingsDataRow>+ </InsetListItem>+ </ListItem>+ ))}+ </InsetList>+ </List>+ </Grid>+ </ScrollArea>+ )}+ </>+ );+};diff --git a/apps/builder/app/shared/project-settings/section-auth.tsx b/apps/builder/app/shared/project-settings/section-auth.tsxindex d766c8dd75..0e6dac8442 100644--- a/apps/builder/app/shared/project-settings/section-auth.tsx+++ b/apps/builder/app/shared/project-settings/section-auth.tsx@@ -1,24 +1,16 @@-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useMemo, useState } from "react";import {Button,- Combobox,Flex,Grid,- InputErrorsTooltip,- InputField,LinkButton,- List,- ListItem,ProChip,- ScrollArea,- SearchField,- SmallIconButton,Text,theme,Tooltip,cssVar,} from "@webstudio-is/design-system";-import { InfoCircleIcon, TrashIcon } from "@webstudio-is/icons";+import { InfoCircleIcon } from "@webstudio-is/icons";import { useStore } from "@nanostores/react";import {createBasicAuthRoute,@@ -34,7 +26,10 @@ import {parseProjectAuthRoutes,validateProjectAuthRoute,} from "@webstudio-is/project-build/contracts";-import { ProjectSettingsDataRow } from "./data-row";+import {+ ProjectSettingsDeleteRuleButton,+ ProjectSettingsRuleList,+} from "./rule-list";const saveAuthRoutes = (authRoutes: WsAuthRoute[]) => {executeRuntimeMutation({@@ -51,17 +46,9 @@ export const SectionAuth = () => {const { allowAuth } = useStore($permissions);const pages = useStore($pages);const projectSettings = useStore($projectSettings);- const routeRef = useRef<HTMLInputElement>(null);const [authRoutes, setAuthRoutes] = useState(() => {return parseProjectAuthRoutes($projectSettings.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 = projectSettings?.meta.auth;const parseResult = useMemo(() => {@@ -75,60 +62,21 @@ export const SectionAuth = () => {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(validateProjectAuthRoute(value.trim(), authRoutes));- };-const handleSave = (nextAuthRoutes: WsAuthRoute[]) => {setAuthRoutes(nextAuthRoutes);saveAuthRoutes(nextAuthRoutes);};- const handleAddAuthRoute = () => {- const nextRoute = route.trim();- const nextRouteErrors = validateProjectAuthRoute(nextRoute, authRoutes);- const basicAuthErrors = validateBasicAuthCredentials({- login,- password,- });- const nextLoginErrors = basicAuthErrors?.login ?? [];- const nextPasswordErrors = basicAuthErrors?.password ?? [];-- setRouteErrors(nextRouteErrors);- setLoginErrors(nextLoginErrors);- setPasswordErrors(nextPasswordErrors);-- if (- nextRouteErrors.length > 0 ||- nextLoginErrors.length > 0 ||- nextPasswordErrors.length > 0- ) {- return;- }-+ const handleAddAuthRoute = (values: Record<string, string>) => {handleSave([createBasicAuthRoute({- route: nextRoute,- login,- password,+ route: values.route.trim(),+ login: values.login,+ password: values.password,}),...authRoutes,]);- setRoute("");- setLogin("");- setPassword("");- routeRef.current?.focus();+ return true;};const handleDeleteAuthRoute = (index: number) => {@@ -138,9 +86,6 @@ export const SectionAuth = () => {};const handleReset = () => {- setRouteErrors([]);- setLoginErrors([]);- setPasswordErrors([]);handleSave([]);};@@ -206,135 +151,53 @@ export const SectionAuth = () => {</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- color="primary"- 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}>- <ProjectSettingsDataRow- align="center"- gap="2"- css={{- gridTemplateColumns: "1fr 1fr",- }}- >- <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)}- />- </ProjectSettingsDataRow>- </ListItem>- );- })}- </Flex>- </List>- </Grid>- </ScrollArea>- ) : null}+ <ProjectSettingsRuleList+ fields={[+ {+ name: "route",+ placeholder: "/private or /docs/*",+ suggestions: routeSuggestions,+ validateOnChange: (value) =>+ validateProjectAuthRoute(value.trim(), authRoutes),+ },+ { name: "login", placeholder: "Login" },+ { name: "password", placeholder: "Password", type: "password" },+ ]}+ validate={(values) => ({+ route: validateProjectAuthRoute(+ values.route?.trim() ?? "",+ authRoutes+ ),+ ...validateBasicAuthCredentials({+ login: values.login ?? "",+ password: values.password ?? "",+ }),+ })}+ onSubmit={handleAddAuthRoute}+ columns="1fr 1fr"+ columnLabels={["Path", "Login"]}+ label="Authentication rules"+ rules={authRoutes.map((authRoute, index) => ({+ key: authRoute.route,+ values: [+ <Tooltip content={authRoute.route} key="route">+ <Text truncate css={{ wordBreak: "break-all" }}>+ {authRoute.route}+ </Text>+ </Tooltip>,+ <Tooltip content={authRoute.auth.login} key="login">+ <Text truncate>{authRoute.auth.login}</Text>+ </Tooltip>,+ ],+ actions: (+ <ProjectSettingsDeleteRuleButton+ label={`Delete authentication for ${authRoute.route}`}+ description={`authentication for ${authRoute.route}`}+ onDelete={() => handleDeleteAuthRoute(index)}+ />+ ),+ }))}+ /></Grid>);};diff --git a/apps/builder/app/shared/project-settings/section-headers.test.tsx b/apps/builder/app/shared/project-settings/section-headers.test.tsxnew file mode 100644index 0000000000..c6b4e1f960--- /dev/null+++ b/apps/builder/app/shared/project-settings/section-headers.test.tsx@@ -0,0 +1,375 @@+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { page } from "@vitest/browser/context";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import { $projectSettings } from "~/shared/sync/data-stores";+import { SectionHeaders } from "./section-headers";++const executeRuntimeMutation = vi.fn(() => ({}) as never);++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root;+let previousSettings: ReturnType<typeof $projectSettings.get>;++beforeEach(() => {+ previousSettings = $projectSettings.get();+ $projectSettings.set({ meta: {}, compiler: {} });+ executeRuntimeMutation.mockReset().mockImplementation(() => ({}) as never);+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ document.body.innerHTML = "";+ $projectSettings.set(previousSettings);+});++const render = () => {+ act(() => {+ root.render(+ <TooltipProvider>+ <SectionHeaders executeMutation={executeRuntimeMutation} />+ </TooltipProvider>+ );+ });+ const route = document.querySelector<HTMLInputElement>(+ 'input[placeholder="/* or /private/*"]'+ );+ const name = document.querySelector<HTMLInputElement>(+ 'input[placeholder="Header name"]'+ );+ const value = document.querySelector<HTMLInputElement>(+ 'input[placeholder="Header value"]'+ );+ if (!route || !name || !value) {+ throw new Error("Expected the rule form");+ }+ return { route, name, value };+};++const type = async (input: HTMLInputElement, value: string) => {+ await act(async () => page.getByPlaceholder(input.placeholder).fill(value));+};++test("offers standard names and values for the selected header", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ const { route, name, value } = render();+ await type(route, "/*");+ await type(name, "Cache");+ const options = () =>+ Array.from(document.querySelectorAll('[role="option"]')).map(+ (option) => option.textContent+ );+ expect(options()).toContain("Cache-Control");+ expect(options()).not.toContain("X-Powered-By");+ await act(async () =>+ page.getByRole("option", { name: "Cache-Control", exact: true }).click()+ );+ expect(+ document.querySelector<HTMLInputElement>('input[placeholder="Header name"]')+ ?.value+ ).toBe("Cache-Control");+ await type(value, "no");+ expect(options()).toContain("no-store");+ await act(async () =>+ page.getByRole("option", { name: "no-store", exact: true }).click()+ );+ expect(+ document.querySelector<HTMLInputElement>(+ 'input[placeholder="Header value"]'+ )?.value+ ).toBe("no-store");+ await act(async () =>+ page.getByRole("button", { name: "Add", exact: true }).click()+ );+ expect(executeRuntimeMutation).toHaveBeenCalledWith({+ id: "projectSettings.update",+ input: {+ meta: {+ customHeaders: [{ name: "Cache-Control", value: "no-store" }],+ },+ },+ });+ expect(+ document.querySelector<HTMLInputElement>('input[placeholder="Header name"]')+ ?.value+ ).toBe("");+ expect(+ document.querySelector<HTMLInputElement>(+ 'input[placeholder="Header value"]'+ )?.value+ ).toBe("");+});++test("Enter in an autocomplete field does not add a rule", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ const { route, name, value } = render();+ await type(route, "/*");+ await type(name, "Cache-Control");+ await type(value, "no-store");+ act(() => {+ value.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "Enter",+ bubbles: true,+ cancelable: true,+ })+ );+ });+ expect(executeRuntimeMutation).not.toHaveBeenCalled();+ const add = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Add"+ );+ act(() => add?.click());+ expect(executeRuntimeMutation).toHaveBeenCalledOnce();+});++test("typing a non-customizable header cannot save a rule", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ const { route, name, value } = render();+ await type(route, "/*");+ await type(name, "sEt-CoOkIe");+ await type(value, "session=override");+ await act(async () =>+ page.getByRole("button", { name: "Add", exact: true }).click()+ );+ expect(executeRuntimeMutation).not.toHaveBeenCalled();+ expect(+ document.querySelector<HTMLInputElement>('input[placeholder="Header name"]')+ ?.value+ ).toBe("sEt-CoOkIe");+});++test.each(["denied", "throws"])(+ "keeps form values and shows an error when saving %s",+ async (failure) => {+ executeRuntimeMutation.mockImplementation(() => {+ if (failure === "throws") {+ throw new Error("Runtime mutation failed");+ }+ return undefined as never;+ });+ const { route, name, value } = render();+ await type(route, "/*");+ await type(name, "Content-Security-Policy");+ await type(value, "frame-ancestors https://example.com");+ await act(async () =>+ page.getByRole("button", { name: "Add", exact: true }).click()+ );+ expect(+ document.querySelector<HTMLInputElement>(+ 'input[placeholder="Header value"]'+ )?.value+ ).toBe("frame-ancestors https://example.com");+ expect(document.body.textContent).toContain("Changes could not be saved");+ expect($projectSettings.get()?.meta.customHeaders).toBeUndefined();+ }+);++test("starts with no rows and adds a route rule", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ render();+ expect(document.querySelector('[role="table"]')).toBeNull();+ const { route, name, value } = {+ route: document.querySelector<HTMLInputElement>(+ 'input[placeholder="/* or /private/*"]'+ ),+ name: document.querySelector<HTMLInputElement>(+ 'input[placeholder="Header name"]'+ ),+ value: document.querySelector<HTMLInputElement>(+ 'input[placeholder="Header value"]'+ ),+ };+ if (!route || !name || !value) {+ throw new Error("Expected the rule form");+ }+ await type(route, "/private/*");+ await type(name, "Referrer-Policy");+ await type(value, "no-referrer");+ const add = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Add"+ );+ act(() => add?.click());+ expect(executeRuntimeMutation).toHaveBeenCalledWith({+ id: "projectSettings.update",+ input: {+ meta: {+ customHeaders: [+ {+ route: "/private/*",+ name: "Referrer-Policy",+ value: "no-referrer",+ },+ ],+ },+ },+ });+});++test("submitting an existing default header updates its value", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ const { route, name, value } = render();+ await type(route, "/*");+ await type(name, "content-security-policy");+ await type(value, "frame-ancestors https://example.com");+ const add = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Add"+ );+ act(() => add?.click());+ expect(executeRuntimeMutation).toHaveBeenCalledWith({+ id: "projectSettings.update",+ input: {+ meta: {+ customHeaders: [+ {+ name: "Content-Security-Policy",+ value: "frame-ancestors https://example.com",+ },+ ],+ },+ },+ });+});++test("saves / as a root-only rule", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ const { route, name, value } = render();+ await type(route, "/");+ await type(name, "Referrer-Policy");+ await type(value, "no-referrer");+ const add = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Add"+ );+ act(() => add?.click());+ expect(executeRuntimeMutation).toHaveBeenCalledWith({+ id: "projectSettings.update",+ input: {+ meta: {+ customHeaders: [+ { route: "/", name: "Referrer-Policy", value: "no-referrer" },+ ],+ },+ },+ });+});++test("adds an arbitrary header and displays existing custom headers", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ $projectSettings.set({+ meta: { customHeaders: [{ name: "Cache-Control", value: "no-store" }] },+ compiler: {},+ });+ const { route, name, value } = render();+ expect(document.body.textContent).toContain("Cache-Control");+ expect(+ document.querySelector('button[aria-label="Remove Cache-Control for /*"]')+ ).not.toBeNull();+ await type(route, "/*");+ await type(name, "Access-Control-Allow-Origin");+ await type(value, "*");+ const add = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Add"+ );+ act(() => add?.click());+ expect(executeRuntimeMutation).toHaveBeenCalledWith({+ id: "projectSettings.update",+ input: {+ meta: {+ customHeaders: [+ { name: "Access-Control-Allow-Origin", value: "*" },+ { name: "Cache-Control", value: "no-store" },+ ],+ },+ },+ });+});++test("deleting a custom site-wide header requires confirmation", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ $projectSettings.set({+ meta: { customHeaders: [{ name: "Cache-Control", value: "no-store" }] },+ compiler: {},+ });+ render();+ await act(async () =>+ page.getByRole("button", { name: "Remove Cache-Control for /*" }).click()+ );+ expect(executeRuntimeMutation).not.toHaveBeenCalled();+ expect(document.body.textContent).toContain("delete Cache-Control for /*");+ await act(async () => {+ await page.getByRole("button", { name: "Cancel" }).click();+ await new Promise(requestAnimationFrame);+ });+ expect(executeRuntimeMutation).not.toHaveBeenCalled();+ await act(async () =>+ page.getByRole("button", { name: "Remove Cache-Control for /*" }).click()+ );+ await act(async () =>+ page.getByRole("button", { name: "Delete", exact: true }).click()+ );+ expect(executeRuntimeMutation).toHaveBeenCalledWith({+ id: "projectSettings.update",+ input: { meta: { customHeaders: null } },+ });+});++test("deleting a configured fallback header leaves no settings rule", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ $projectSettings.set({+ meta: {+ customHeaders: [+ { name: "Content-Security-Policy", value: "frame-ancestors 'none'" },+ ],+ },+ compiler: {},+ });+ render();+ await act(async () =>+ page+ .getByRole("button", { name: "Remove Content-Security-Policy for /*" })+ .click()+ );+ await act(async () =>+ page.getByRole("button", { name: "Delete", exact: true }).click()+ );+ expect(executeRuntimeMutation).toHaveBeenCalledWith({+ id: "projectSettings.update",+ input: { meta: { customHeaders: null } },+ });+});++test("shows an error when confirmed deletion cannot be saved", async () => {+ executeRuntimeMutation.mockReturnValue(undefined as never);+ $projectSettings.set({+ meta: { customHeaders: [{ name: "Cache-Control", value: "no-store" }] },+ compiler: {},+ });+ render();+ await act(async () =>+ page.getByRole("button", { name: "Remove Cache-Control for /*" }).click()+ );+ await act(async () =>+ page.getByRole("button", { name: "Delete", exact: true }).click()+ );+ expect(document.body.textContent).toContain("Changes could not be saved");+ expect(document.body.textContent).toContain("Cache-Control");+});++test("empty route value cannot create a fallback-header rule", async () => {+ executeRuntimeMutation.mockReturnValue({} as never);+ const { route, name } = render();+ await type(route, "/private/*");+ await type(name, "Content-Security-Policy");+ const add = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Add"+ );+ act(() => add?.click());+ expect(executeRuntimeMutation).not.toHaveBeenCalled();+});diff --git a/apps/builder/app/shared/project-settings/section-headers.tsx b/apps/builder/app/shared/project-settings/section-headers.tsxnew file mode 100644index 0000000000..9fd9d499e0--- /dev/null+++ b/apps/builder/app/shared/project-settings/section-headers.tsx@@ -0,0 +1,233 @@+import { useState } from "react";+import { useStore } from "@nanostores/react";+import {+ Flex,+ Grid,+ LinkButton,+ ProChip,+ Text,+ Tooltip,+ cssVar,+ theme,+} from "@webstudio-is/design-system";+import { InfoCircleIcon } from "@webstudio-is/icons";+import {+ customResponseHeader,+ customResponseHeaders,+ getResponseHeaderDefinition,+ type CustomResponseHeader,+} from "@webstudio-is/sdk";+import { validateWsAuthRoute } from "@webstudio-is/wsauth";+import { $pages, $projectSettings } from "~/shared/sync/data-stores";+import { $permissions } from "~/shared/nano-states";+import { executeRuntimeMutation } from "~/shared/instance-utils/data";+import {+ ProjectSettingsDeleteRuleButton,+ ProjectSettingsRuleList,+} from "./rule-list";+import {+ getResponseHeaderName,+ getResponseHeaderValueSuggestions,+ responseHeaderNames,+} from "./response-header-suggestions";+import { getExistingRoutePaths, sectionSpacing } from "./utils";++const ruleKey = (route: string, name: string) =>+ `${route}\0${name.toLowerCase()}`;++export const SectionHeaders = ({+ executeMutation = executeRuntimeMutation,+}: {+ projectId?: string;+ executeMutation?: (+ args: Parameters<typeof executeRuntimeMutation>[0]+ ) => ReturnType<typeof executeRuntimeMutation>;+} = {}) => {+ const { allowDynamicData } = useStore($permissions);+ const settings = useStore($projectSettings);+ const pages = useStore($pages);+ const [saveError, setSaveError] = useState("");+ const configured = settings?.meta.customHeaders ?? [];+ const routeSuggestions = [+ ...new Set(["/*", "/", ...Array.from(getExistingRoutePaths(pages)).sort()]),+ ];++ const save = (+ next: CustomResponseHeader | undefined,+ previousKey?: string+ ) => {+ const headers = ($projectSettings.get()?.meta.customHeaders ?? []).filter(+ (header) => ruleKey(header.route ?? "/*", header.name) !== previousKey+ );+ if (next !== undefined) {+ headers.unshift(next);+ }+ const result = customResponseHeaders.safeParse(headers);+ if (!result.success) {+ setSaveError(+ result.error.issues.map((issue) => issue.message).join(". ")+ );+ return false;+ }+ try {+ const mutation = executeMutation({+ id: "projectSettings.update",+ input: {+ meta: { customHeaders: result.data.length ? result.data : null },+ },+ });+ if (mutation !== undefined) {+ setSaveError("");+ return true;+ }+ } catch {+ // Keep the form values or existing row available for retry.+ }+ setSaveError("Changes could not be saved. Please try again.");+ return false;+ };++ return (+ <Grid gap={3} css={sectionSpacing}>+ <Flex align="center" gap={1}>+ <Text variant="titles">Headers</Text>+ {allowDynamicData === false && <ProChip>Pro</ProChip>}+ <Tooltip+ variant="wrapped"+ content={+ <>+ <Text>+ Set response headers for all paths or a route. Routes use the+ same syntax as Authentication, including :params and *.+ </Text>+ <br />+ <Text>+ /* applies to every path; / applies only to the root. Webstudio+ Cloud supplies CSP, X-Frame-Options, and Referrer-Policy when+ they are not set. X-Powered-By, X-Content-Type-Options, and+ Strict-Transport-Security are managed by the platform and cannot+ be configured here. Cookie, connection, and response-body+ framing headers are also unavailable. Publish to apply changes.+ </Text>+ {allowDynamicData === false && (+ <>+ <br />+ <Text>+ Custom headers on a custom domain require Pro. Defaults and+ staging are free.+ </Text>+ <LinkButton+ color="primary"+ css={{ marginTop: theme.spacing[5], width: "100%" }}+ href="https://webstudio.is/pricing"+ target="_blank"+ >+ Upgrade+ </LinkButton>+ </>+ )}+ </>+ }+ >+ <InfoCircleIcon+ color={cssVar("--foreground-secondary")}+ tabIndex={0}+ aria-label="About response headers"+ />+ </Tooltip>+ </Flex>+ {saveError && <Text color="destructive">{saveError}</Text>}+ <ProjectSettingsRuleList+ fields={[+ {+ name: "route",+ placeholder: "/* or /private/*",+ suggestions: routeSuggestions,+ },+ {+ name: "name",+ placeholder: "Header name",+ suggestions: responseHeaderNames,+ },+ {+ name: "value",+ placeholder: "Header value",+ suggestions: (values) =>+ getResponseHeaderValueSuggestions(values.name ?? ""),+ },+ ]}+ validate={(values) => {+ const route = values.route?.trim() ?? "";+ const name = values.name?.trim() ?? "";+ const value = values.value?.trim() ?? "";+ const errors: Record<string, string[]> = {};+ const routeError = validateWsAuthRoute(route);+ if (routeError) {+ errors.route = [routeError];+ }+ if (+ value === "" &&+ (route === "/*" || getResponseHeaderDefinition(name) !== undefined)+ ) {+ errors.value = ["Enter a header value"];+ }+ const result = customResponseHeader.safeParse({+ route,+ name,+ value: value === "" ? null : value,+ });+ if (!result.success) {+ for (const issue of result.error.issues) {+ const field = String(issue.path[0] ?? "value");+ (errors[field] ??= []).push(issue.message);+ }+ }+ return errors;+ }}+ onSubmit={(values) => {+ const route = values.route.trim();+ const value = values.value?.trim();+ const name =+ getResponseHeaderName(values.name.trim()) ?? values.name.trim();+ const next: CustomResponseHeader = {+ ...(route === "/*" ? {} : { route }),+ name,+ value: value || null,+ };+ return save(next, ruleKey(route, name));+ }}+ columns="1fr 1.5fr 1.5fr"+ columnLabels={["Path", "Header", "Value"]}+ label="Response header rules"+ rules={configured.map((header) => {+ const route = header.route ?? "/*";+ const key = ruleKey(route, header.name);+ const value =+ header.value ??+ (getResponseHeaderDefinition(header.name) ? "Default" : "Not sent");+ return {+ key,+ values: [+ <Tooltip content={route} key="route">+ <Text truncate>{route}</Text>+ </Tooltip>,+ <Tooltip content={header.name} key="name">+ <Text truncate>{header.name}</Text>+ </Tooltip>,+ <Tooltip content={value} key="value">+ <Text truncate>{value}</Text>+ </Tooltip>,+ ],+ actions: (+ <ProjectSettingsDeleteRuleButton+ label={`Remove ${header.name} for ${route}`}+ description={`${header.name} for ${route}`}+ onDelete={() => save(undefined, key)}+ />+ ),+ };+ })}+ />+ </Grid>+ );+};diff --git a/apps/builder/e2e/tests/project-settings-runtime.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/project-settings-runtime.[shard-2].[shard-5].[shard-6].e2e.tsindex 41d39b9f33..0f3ad5e6c6 100644--- a/apps/builder/e2e/tests/project-settings-runtime.[shard-2].[shard-5].[shard-6].e2e.ts+++ b/apps/builder/e2e/tests/project-settings-runtime.[shard-2].[shard-5].[shard-6].e2e.ts@@ -161,6 +161,7 @@ const deleteBasicAuth = async ({await page.getByRole("button", { name: `Delete authentication for ${route}` }).click();+ await page.getByRole("button", { name: "Delete", exact: true }).click();await save;await waitForSyncStatus({ page, status: "idle" });};diff --git a/docs/university/foundations/project-settings.md b/docs/university/foundations/project-settings.mdindex ab6ccd2aba..5115d9c841 100644--- a/docs/university/foundations/project-settings.md+++ b/docs/university/foundations/project-settings.md@@ -144,6 +144,28 @@ Authentication is a Pro feature for custom domains. You can publish to staging fFor a single page, you can also configure authentication directly in [Page settings](page-settings.md#authentication).+## Headers++Use **Project settings > Headers** to configure your site's HTTP security response headers. Each header starts with a default value:++| Header | Default | Required |+| --- | --- | --- |+| Content-Security-Policy | `frame-ancestors 'self'` | Yes |+| X-Frame-Options | `SAMEORIGIN` | No |+| X-Content-Type-Options | `nosniff` | Yes |+| Referrer-Policy | `strict-origin-when-cross-origin` | Yes |+| Strict-Transport-Security | `max-age=63072000; includeSubDomains; preload` | Yes |++Edit values directly in their fields. Changes are saved when you leave a field or press Enter; Escape cancels an unsaved edit. Required headers cannot be removed or left empty. Use the trash icon to remove X-Frame-Options and the reset icon to restore a header’s default value. Publish to apply changes.++On Webstudio Cloud, changing the defaults or removing an optional header requires Pro when publishing to a custom domain. Default values and staging are free. Platform headers such as `X-Powered-By` are not configurable.++To allow embedding by `https://example.com`, change Content-Security-Policy to `frame-ancestors 'self' https://example.com` and remove X-Frame-Options.++These are standard HTTP headers. Webstudio Cloud applies the settings automatically to site responses, including redirects and site errors. Static assets served by the CDN keep their existing headers. On other hosts, your server or hosting adapter must apply the configuration generated by the CLI in `app/__generated__/$resources.headers.server.ts`, and any proxy or CDN must preserve the resulting headers. Other hosting templates and static exports do not apply these settings automatically.++Header names are case-insensitive. Each header can be configured once, with values up to 8 KB and a combined limit of 16 KB. Values cannot contain line breaks. Arbitrary headers, including cache directives and cookies, cannot be configured in these settings.+## MarketplaceYou can contribute free or paid templates by creating a Project and submitting it for review. Approved templates will appear in the [Marketplace](../marketplace.md).diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.jsonindex 9e06cf4de6..f94dca7290 100644--- a/fixtures/react-router-cloudflare/.webstudio/data.json+++ b/fixtures/react-router-cloudflare/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-zql42m",+ "bundleVersion": "bundle-1fx8bdt","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.jsonindex 9e06cf4de6..f94dca7290 100644--- a/fixtures/react-router-docker/.webstudio/data.json+++ b/fixtures/react-router-docker/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-zql42m",+ "bundleVersion": "bundle-1fx8bdt","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.jsonindex 9e06cf4de6..f94dca7290 100644--- a/fixtures/react-router-netlify/.webstudio/data.json+++ b/fixtures/react-router-netlify/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-zql42m",+ "bundleVersion": "bundle-1fx8bdt","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.jsonindex 9e06cf4de6..f94dca7290 100644--- a/fixtures/react-router-vercel/.webstudio/data.json+++ b/fixtures/react-router-vercel/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-zql42m",+ "bundleVersion": "bundle-1fx8bdt","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.jsonindex 51fb65f95c..6199577c04 100644--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-zql42m",+ "bundleVersion": "bundle-1fx8bdt","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex c7091ab809..ab1b350348 100644--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-zql42m",+ "bundleVersion": "bundle-1fx8bdt","build": {"id": "823cc69d-b2ed-418b-823c-2efc717319cd","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.jsonindex 51fb65f95c..6199577c04 100644--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-zql42m",+ "bundleVersion": "bundle-1fx8bdt","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.jsonindex 1c54514585..3b35bc85d0 100644--- a/fixtures/webstudio-features/.webstudio/data.json+++ b/fixtures/webstudio-features/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-zql42m",+ "bundleVersion": "bundle-1fx8bdt","build": {"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32","projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.tsindex 78469800b3..851503638a 100644--- a/packages/cli/src/commands/schema.test.ts+++ b/packages/cli/src/commands/schema.test.ts@@ -149,7 +149,8 @@ test("prints compact mcp tool summaries as json by default", () => {inputSchema,}));- expect(JSON.stringify(handshakePayload).length).toBeLessThan(217_000);+ // Includes the custom response headers schema in project settings updates.+ expect(JSON.stringify(handshakePayload).length).toBeLessThan(218_000);expect(JSON.stringify(expectedTools.find(({ name }) => name === "insert-page-transfer-item")diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.tsindex 74c6a44be4..d1528d07a7 100644--- a/packages/cli/src/prebuild.test.ts+++ b/packages/cli/src/prebuild.test.ts@@ -51,6 +51,7 @@ import {materializeAssetIndex,prebuild,} from "./prebuild";+import { generateResponseHeadersModule } from "./response-headers";const createSsgAssetResourceFetch = (options: {deploymentId: string;@@ -787,6 +788,44 @@ test("hydrates encoded filenames from an embedded SSG database", async () => {});describe("prebuild", () => {+ test("publishes custom headers and refreshes them on incremental builds", async () => {+ const projectSettings = {+ meta: {+ customHeaders: [+ {+ name: "Content-Security-Policy",+ value: "frame-ancestors https://example.com",+ },+ { name: "X-Frame-Options", value: null },+ ],+ },+ compiler: {},+ };+ const data = createSiteData();+ const bundle = { ...data, build: { ...data.build, projectSettings } };+ await writeFile(".webstudio/data.json", JSON.stringify(bundle));+ await prebuild({+ assets: false,+ template: ["defaults"],+ preserveRouteTemplates: true,+ });+ const file = "app/__generated__/$resources.headers.server.ts";+ await expect(readFile(file, "utf8")).resolves.toBe(+ generateResponseHeadersModule(projectSettings)+ );++ bundle.build.projectSettings.meta.customHeaders = [];+ await writeFile(".webstudio/data.json", JSON.stringify(bundle));+ await prebuild({+ assets: false,+ template: ["defaults"],+ incremental: true,+ });+ await expect(readFile(file, "utf8")).resolves.toBe(+ generateResponseHeadersModule()+ );+ });+test.each(["defaults", "react-router", "ssg"])("does not scaffold a default root favicon with the %s template",async (template) => {diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex 93fdb2b545..68eabd7a7a 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -110,6 +110,7 @@ import {type PublishedProjectBundle,} from "@webstudio-is/protocol";import { createAuthConfigResources, LOCAL_AUTH_FILE } from "./auth-config";+import { generateResponseHeadersModule } from "./response-headers";import { LOCAL_DATA_FILE } from "./config";import {createFileIfNotExists,@@ -1095,6 +1096,10 @@ export const prebuild = async (options: {siteData.build.projectSettings,writeGeneratedFile);+ await writeGeneratedFile(+ join(generatedDir, "$resources.headers.server.ts"),+ generateResponseHeadersModule(siteData.build.projectSettings)+ );const siteDataByPage: SiteDataByPage = {};const fontAssetsByPage: Record<Page["id"], string[]> = {};const backgroundImageAssetsByPage: Record<Page["id"], string[]> = {};diff --git a/packages/cli/src/response-headers.test.ts b/packages/cli/src/response-headers.test.tsnew file mode 100644index 0000000000..cfbe87d8a3--- /dev/null+++ b/packages/cli/src/response-headers.test.ts@@ -0,0 +1,49 @@+import { runInNewContext } from "node:vm";+import { transformSync } from "esbuild";+import { expect, test } from "vitest";+import { generateResponseHeadersModule } from "./response-headers";++const readGeneratedHeaders = (source: string) => {+ const { code } = transformSync(source, { loader: "ts", format: "cjs" });+ const module = { exports: {} as { customHeaders?: unknown } };+ runInNewContext(code, { module });+ return module.exports.customHeaders;+};++test("generates no user rules for existing projects", () => {+ expect(readGeneratedHeaders(generateResponseHeadersModule())).toEqual([]);+});++test("compiles configured values and route rules as data", () => {+ const headers = [+ {+ name: "Content-Security-Policy",+ value: "frame-ancestors https://example.com",+ },+ { route: "/docs/*", name: "Referrer-Policy", value: "no-referrer" },+ { name: "Cache-Control", value: "public, max-age=60" },+ ];+ expect(+ readGeneratedHeaders(+ generateResponseHeadersModule({+ meta: { customHeaders: headers },+ compiler: {},+ })+ )+ ).toEqual(headers);+});++test("invalid or dispatcher-owned configuration fails the build", () => {+ for (const header of [+ { name: "Content-Security-Policy", value: "bad\r\nvalue" },+ { name: "X-Content-Type-Options", value: "off" },+ { name: "Strict-Transport-Security", value: "max-age=0" },+ ]) {+ expect(() =>+ generateResponseHeadersModule({+ meta: { customHeaders: [header] },+ compiler: {},+ })+ ).toThrow();+ }+});diff --git a/packages/cli/src/response-headers.ts b/packages/cli/src/response-headers.tsnew file mode 100644index 0000000000..66f008d785--- /dev/null+++ b/packages/cli/src/response-headers.ts@@ -0,0 +1,15 @@+import { customResponseHeaders } from "@webstudio-is/sdk/schema";+import type { ProjectSettings } from "@webstudio-is/project-build";++export const generateResponseHeadersModule = (settings?: ProjectSettings) => {+ const configured = customResponseHeaders.parse(+ settings?.meta.customHeaders ?? []+ );+ return `// Generated response header configuration for hosting adapters.+export const customHeaders: Array<{ route?: string; name: string; value: string | null }> = ${JSON.stringify(+ configured,+ null,+ 2+ )};+`;+};diff --git a/packages/design-system/src/components/combobox.tsx b/packages/design-system/src/components/combobox.tsxindex 88ec814d61..5b5cbada45 100644--- a/packages/design-system/src/components/combobox.tsx+++ b/packages/design-system/src/components/combobox.tsx@@ -171,7 +171,7 @@ export const ComboboxItemDescription = ({};export const ComboboxRoot = (props: ComponentProps<typeof Popover>) => {- return <Popover {...props} modal />;+ return <Popover modal {...props} />;};const StyledPopoverContent = styled(PopoverContent, {@@ -473,7 +473,7 @@ type ComboboxProps<Item> = UseComboboxProps<Item> &| "onBlur"| "onInvalid"| "disabled"- >;+ > & { modal?: boolean };export const Combobox = <Item,>({getDescription,@@ -487,6 +487,7 @@ export const Combobox = <Item,>({onBlur,onInvalid,disabled,+ modal,...props}: ComboboxProps<Item>) => {const combobox = useCombobox<Item>(props);@@ -500,7 +501,7 @@ export const Combobox = <Item,>({const descriptions = combobox.items.map((item) => getDescription?.(item));return (- <ComboboxRoot open={combobox.isOpen}>+ <ComboboxRoot open={combobox.isOpen} modal={modal ?? true}><Box {...combobox.getComboboxProps()}><ComboboxAnchor><InputFielddiff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex 7e202b7ddc..da9438343c 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -5403,6 +5403,38 @@ export const runtimeOperationContractData = [auth: {type: "string",},+ customHeaders: {+ description:+ "Response header rules. Optional route patterns use Authentication syntax; '/*' applies site-wide. Missing CSP, X-Frame-Options, and Referrer-Policy receive dispatcher defaults. X-Powered-By, X-Content-Type-Options, and Strict-Transport-Security are managed by Webstudio Cloud.",+ maxItems: 100,+ type: "array",+ items: {+ type: "object",+ properties: {+ route: {+ type: "string",+ maxLength: 2048,+ },+ name: {+ type: "string",+ maxLength: 256,+ },+ value: {+ anyOf: [+ {+ type: "string",+ maxLength: 8192,+ pattern: "^[\\t\\x20-\\x7e\\x80-\\xff]*$(?![\\s\\S])",+ },+ {+ type: "null",+ },+ ],+ },+ },+ required: ["name", "value"],+ },+ },},additionalProperties: {},required: [],@@ -5518,6 +5550,46 @@ export const runtimeOperationContractData = [},],},+ customHeaders: {+ anyOf: [+ {+ description:+ "Response header rules. Optional route patterns use Authentication syntax; '/*' applies site-wide. Missing CSP, X-Frame-Options, and Referrer-Policy receive dispatcher defaults. X-Powered-By, X-Content-Type-Options, and Strict-Transport-Security are managed by Webstudio Cloud.",+ maxItems: 100,+ type: "array",+ items: {+ type: "object",+ properties: {+ route: {+ type: "string",+ maxLength: 2048,+ },+ name: {+ type: "string",+ maxLength: 256,+ },+ value: {+ anyOf: [+ {+ type: "string",+ maxLength: 8192,+ pattern:+ "^[\\t\\x20-\\x7e\\x80-\\xff]*$(?![\\s\\S])",+ },+ {+ type: "null",+ },+ ],+ },+ },+ required: ["name", "value"],+ },+ },+ {+ type: "null",+ },+ ],+ },},additionalProperties: false,required: [],diff --git a/packages/project-build/src/db/build.test.ts b/packages/project-build/src/db/build.test.tsindex 62be3730d7..1846ea124b 100644--- a/packages/project-build/src/db/build.test.ts+++ b/packages/project-build/src/db/build.test.ts@@ -1,4 +1,4 @@-import { describe, test, expect } from "vitest";+import { describe, test, expect, vi } from "vitest";import {createTestServer,db,@@ -375,6 +375,257 @@ describe("createBuild (msw)", () => {// ---------------------------------------------------------------------------describe("createProductionBuild (msw)", () => {+ test.each([+ {+ label: "Free owner, custom domain",+ allowed: false,+ domains: ["example.com"],+ headers: [{ name: "X-Frame-Options", value: "DENY" }],+ denied: true,+ checkPlan: true,+ },+ {+ label: "Free owner, legacy null fallback",+ allowed: false,+ domains: ["example.com"],+ headers: [{ name: "X-Frame-Options", value: null }],+ denied: false,+ checkPlan: false,+ },+ {+ label: "Free owner, route rule",+ allowed: false,+ domains: ["example.com"],+ headers: [+ {+ route: "/private/*",+ name: "Referrer-Policy",+ value: "no-referrer",+ },+ ],+ denied: true,+ checkPlan: true,+ },+ {+ label: "Free owner, mixed domains",+ allowed: false,+ domains: ["project-domain", "example.com"],+ headers: [{ name: "X-Frame-Options", value: "DENY" }],+ denied: true,+ checkPlan: true,+ },+ {+ label: "Free owner, staging",+ allowed: false,+ domains: ["project-domain"],+ headers: [{ name: "X-Frame-Options", value: "DENY" }],+ denied: false,+ checkPlan: false,+ },+ {+ label: "Pro owner, custom domain",+ allowed: true,+ domains: ["example.com"],+ headers: [{ name: "X-Frame-Options", value: "DENY" }],+ denied: false,+ checkPlan: true,+ },+ {+ label: "Free owner, deleted headers",+ allowed: false,+ domains: ["example.com"],+ headers: [],+ denied: false,+ checkPlan: false,+ },+ {+ label: "Free owner, explicit defaults",+ allowed: false,+ domains: ["example.com"],+ headers: [+ { name: "content-security-policy", value: "frame-ancestors 'self'" },+ { name: "X-Frame-Options", value: "SAMEORIGIN" },+ ],+ denied: false,+ checkPlan: false,+ },+ ])(+ "enforces custom header publishing for $label",+ async ({ allowed, domains, headers, denied, checkPlan }) => {+ const context = createContext();+ // A collaborator's own plan must not determine the project's entitlement.+ context.planFeatures = {+ ...context.planFeatures,+ allowDynamicData: !allowed,+ };+ const getOwnerPlanFeatures = vi.fn(async () => ({+ ...context.planFeatures,+ allowDynamicData: allowed,+ }));+ context.getOwnerPlanFeatures = getOwnerPlanFeatures;+ const createBuild = vi.fn(() => json("build-prod"));+ const removeBuild = vi.fn(() => empty({ status: 204 }));+ server.use(+ db.get("Project", () =>+ json({+ id: "proj-1",+ userId: "project-owner",+ domain: "project-domain",+ })+ ),+ db.get("Build", () =>+ json([+ {+ ...buildRow,+ projectSettings: JSON.stringify({+ meta: { customHeaders: headers },+ compiler: {},+ }),+ },+ ])+ ),+ db.post("rpc/create_production_build", createBuild),+ db.delete("Build", removeBuild)+ );+ const result = createProductionBuild(+ {+ projectId: "proj-1",+ deployment: {+ destination: "saas",+ domains,+ // Deliberately misleading caller-supplied metadata must not bypass the gate.+ target: "staging",+ assetsDomain: domains[0],+ },+ },+ context+ );+ if (denied) {+ await expect(result).rejects.toThrow(+ "Custom headers are a Pro feature"+ );+ expect(removeBuild).toHaveBeenCalledOnce();+ } else {+ await expect(result).resolves.toEqual({ id: "build-prod" });+ expect(removeBuild).not.toHaveBeenCalled();+ }+ expect(createBuild).toHaveBeenCalledOnce();+ if (checkPlan) {+ expect(getOwnerPlanFeatures).toHaveBeenCalledExactlyOnceWith(+ "project-owner"+ );+ } else {+ expect(getOwnerPlanFeatures).not.toHaveBeenCalled();+ }+ }+ );++ test.each([+ { label: "custom value", value: "DENY", allowed: false, staging: false },+ {+ label: "legacy null fallback",+ value: null,+ allowed: false,+ staging: false,+ },+ { label: "Pro owner", value: "DENY", allowed: true, staging: false },+ { label: "staging", value: "DENY", allowed: false, staging: true },+ {+ label: "default value",+ value: "SAMEORIGIN",+ allowed: false,+ staging: false,+ },+ ])(+ "checks the published snapshot after a concurrent edit: $label",+ async ({ value, allowed, staging }) => {+ const context = createContext();+ context.getOwnerPlanFeatures = vi.fn(async () => ({+ ...context.planFeatures,+ allowDynamicData: allowed,+ }));+ const removeBuild = vi.fn(({ request }: { request: Request }) => {+ expect(new URL(request.url).searchParams.get("id")).toBe(+ "eq.build-prod"+ );+ return empty({ status: 204 });+ });+ const readSnapshot = vi.fn();+ server.use(+ db.get("Project", () =>+ json({+ id: "proj-1",+ userId: "project-owner",+ domain: "project-domain",+ })+ ),+ db.get("Build", ({ request }) => {+ const url = new URL(request.url);+ if (url.searchParams.get("id") === "eq.build-prod") {+ readSnapshot();+ expect(url.searchParams.get("select")).toBe("projectSettings");+ return json([+ {+ projectSettings: JSON.stringify({+ meta: { customHeaders: [{ name: "X-Frame-Options", value }] },+ compiler: {},+ }),+ },+ ]);+ }+ // Development settings change before the RPC snapshots them.+ return json([buildRow]);+ }),+ db.post("rpc/create_production_build", () => json("build-prod")),+ db.delete("Build", removeBuild)+ );+ const result = createProductionBuild(+ {+ projectId: "proj-1",+ deployment: {+ destination: "saas",+ domains: [staging ? "project-domain" : "example.com"],+ },+ },+ context+ );+ if (!allowed && !staging && value !== "SAMEORIGIN" && value !== null) {+ await expect(result).rejects.toThrow(+ "Custom headers are a Pro feature"+ );+ expect(removeBuild).toHaveBeenCalledOnce();+ } else {+ await expect(result).resolves.toEqual({ id: "build-prod" });+ expect(removeBuild).not.toHaveBeenCalled();+ }+ expect(readSnapshot).toHaveBeenCalledOnce();+ }+ );++ test("fails closed and removes the unpublished build when its settings cannot be verified", async () => {+ const removeBuild = vi.fn(() => empty({ status: 204 }));+ server.use(+ ownershipHandler,+ db.get("Build", ({ request }) =>+ new URL(request.url).searchParams.has("id")+ ? json([])+ : json([buildRow])+ ),+ db.post("rpc/create_production_build", () => json("build-prod")),+ db.delete("Build", removeBuild)+ );+ await expect(+ createProductionBuild(+ {+ projectId: "proj-1",+ deployment: { destination: "saas", domains: ["example.com"] },+ },+ createContext()+ )+ ).rejects.toThrow("Cannot verify published response headers");+ expect(removeBuild).toHaveBeenCalledOnce();+ });+test("throws when dev build has orphan resource references", async () => {let didCreateProductionBuild = false;server.use(diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.tsindex 4a610cc3ae..0a205bb20e 100644--- a/packages/project-build/src/db/build.ts+++ b/packages/project-build/src/db/build.ts@@ -2,11 +2,13 @@ import type { Database } from "@webstudio-is/postgrest/index.server";import {AuthorizationError,authorizeProject,+ getProjectPlanFeatures,type AppContext,} from "@webstudio-is/trpc-interface/index.server";import { db as authDb } from "@webstudio-is/authorization-token/index.server";import {createId,+ hasCustomResponseHeaders,dataSource,type Deployment,type Resource,@@ -436,8 +438,65 @@ export const createProductionBuild = async (throw Error(`Project ${props.projectId} not found`);}+ if (props.deployment.destination === "static") {+ return { id: buildId };+ }++ try {+ // Check the saved snapshot so concurrent development edits cannot bypass+ // the Pro requirement. The caller publishes only after this check passes.+ const snapshot = await context.postgrest.client+ .from("Build")+ .select("projectSettings")+ .eq("id", buildId);+ if (snapshot.error) {+ throw snapshot.error;+ }+ if (snapshot.data.length !== 1) {+ throw new Error("Cannot verify published response headers");+ }+ const settings = projectSettings.parse(+ parseConfig<unknown>(snapshot.data[0].projectSettings)+ );+ if (!hasCustomResponseHeaders(settings.meta.customHeaders)) {+ return { id: buildId };+ }+ // Use the saved staging domain, not caller-supplied deployment metadata.+ const project = await context.postgrest.client+ .from("Project")+ .select("domain")+ .eq("id", props.projectId)+ .single();+ if (project.error) {+ throw project.error;+ }+ if (+ props.deployment.domains.every((domain) => domain === project.data.domain)+ ) {+ return { id: buildId };+ }+ const plan = await getProjectPlanFeatures(props.projectId, context);+ if (plan.allowDynamicData !== true) {+ throw new AuthorizationError(+ "Custom headers are a Pro feature. Upgrade to Pro or reset the response headers to defaults to publish to custom domains. You can still publish to staging."+ );+ }+ } catch (error) {+ const cleanup = await context.postgrest.client+ .from("Build")+ .delete()+ .eq("id", buildId);+ if (cleanup.error) {+ throw new AggregateError(+ [error, cleanup.error],+ "Could not verify response headers or remove the unpublished build"+ );+ }+ throw error;+ }+return {- id: build.data,+ id: buildId,};};diff --git a/packages/project-build/src/runtime/project-settings.test.ts b/packages/project-build/src/runtime/project-settings.test.tsindex 60c3284126..e89439c4b6 100644--- a/packages/project-build/src/runtime/project-settings.test.ts+++ b/packages/project-build/src/runtime/project-settings.test.ts@@ -82,6 +82,41 @@ const context = {};describe("project settings runtime", () => {+ test("saves custom headers and removes the configuration to restore defaults", () => {+ const customHeaders = [+ { name: "X-Frame-Options", value: null },+ {+ name: "Content-Security-Policy",+ value: "frame-ancestors https://example.com",+ },+ ];+ const input = projectSettingsUpdateInput.parse({ meta: { customHeaders } });+ const state = createState();+ expect(updateProjectSettings(state, input).payload[0]?.patches).toEqual([+ { op: "add", path: ["meta", "customHeaders"], value: customHeaders },+ ]);+ state.projectSettings!.meta.customHeaders = customHeaders;+ expect(+ updateProjectSettings(state, { meta: { customHeaders: null } }).payload[0]+ ?.patches+ ).toEqual([{ op: "remove", path: ["meta", "customHeaders"] }]);+ });++ test("rejects malformed custom headers at the API boundary", () => {+ expect(+ projectSettingsUpdateInput.safeParse({+ meta: {+ customHeaders: [+ {+ name: "Content-Security-Policy",+ value: "safe\r\nX-Injected: true",+ },+ ],+ },+ }).success+ ).toBe(false);+ });+test("exports reusable input contracts for router adapters", () => {expect(projectSettingsUpdateInput.parse({diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.tsindex 9d035a7c35..318f6f1e51 100644--- a/packages/sdk/src/index.ts+++ b/packages/sdk/src/index.ts@@ -2,6 +2,7 @@ export * from "./schema/assets";export * from "./schema/asset-resource";export * from "./schema/asset-folders";export * from "./schema/pages";+export * from "./schema/response-headers";export * from "./schema/instances";export * from "./schema/expression";export * from "./schema/data-sources";diff --git a/packages/sdk/src/schema.ts b/packages/sdk/src/schema.tsindex 3b04ba524c..6ad430613c 100644--- a/packages/sdk/src/schema.ts+++ b/packages/sdk/src/schema.ts@@ -11,6 +11,7 @@ export * from "./schema/deployment";export * from "./schema/instances";export * from "./schema/expression";export * from "./schema/pages";+export * from "./schema/response-headers";export * from "./schema/props";export * from "./schema/resources";export * from "./schema/style-source-selections";diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.tsindex 2a237fc38d..8d3ed03cbf 100644--- a/packages/sdk/src/schema/pages.ts+++ b/packages/sdk/src/schema/pages.ts@@ -1,5 +1,6 @@import { z } from "zod";import { validateBasicAuth } from "@webstudio-is/wsauth";+import { customResponseHeaders } from "./response-headers";export type System = {params: Record<string, string | undefined>;@@ -219,6 +220,11 @@ export const projectMeta = z.object({code: z.string().optional(),agentInstructions: z.string().optional(),auth: z.string().optional(),+ customHeaders: customResponseHeaders+ .optional()+ .describe(+ "Response header rules. Optional route patterns use Authentication syntax; '/*' applies site-wide. Missing CSP, X-Frame-Options, and Referrer-Policy receive dispatcher defaults. X-Powered-By, X-Content-Type-Options, and Strict-Transport-Security are managed by Webstudio Cloud."+ ),});export type ProjectMeta = z.infer<typeof projectMeta>;diff --git a/packages/sdk/src/schema/response-headers.test.ts b/packages/sdk/src/schema/response-headers.test.tsnew file mode 100644index 0000000000..4096903d15--- /dev/null+++ b/packages/sdk/src/schema/response-headers.test.ts@@ -0,0 +1,133 @@+import { describe, expect, test } from "vitest";+import { projectMeta } from "./pages";+import {+ customResponseHeader,+ customResponseHeaders,+ hasCustomResponseHeaders,+ responseHeaderDefinitions,+ forbiddenCustomResponseHeaderNames,+} from "./response-headers";++describe("response header settings", () => {+ test("settings start empty and explicit fallback values are not Pro customizations", () => {+ expect(projectMeta.parse({})).toEqual({});+ expect(hasCustomResponseHeaders()).toBe(false);+ expect(+ hasCustomResponseHeaders(+ responseHeaderDefinitions.map(({ name, defaultValue }) => ({+ name,+ value: defaultValue,+ }))+ )+ ).toBe(false);+ });++ test("supports custom values and routes", () => {+ const headers = [+ {+ name: "Content-Security-Policy",+ value: "frame-ancestors https://example.com",+ },+ { route: "/docs/*", name: "Referrer-Policy", value: "no-referrer" },+ { name: "Cache-Control", value: "public, max-age=60" },+ ];+ expect(customResponseHeaders.parse(headers)).toEqual(headers);+ expect(hasCustomResponseHeaders(headers)).toBe(true);+ expect(+ customResponseHeaders.safeParse([+ { route: "/docs/*", name: "Referrer-Policy", value: "no-referrer" },+ { route: "/docs/*", name: "referrer-policy", value: "same-origin" },+ ]).success+ ).toBe(false);+ expect(+ customResponseHeader.safeParse({+ route: "/docs/*/bad",+ name: "Referrer-Policy",+ value: "no-referrer",+ }).success+ ).toBe(false);+ });++ test.each(responseHeaderDefinitions)(+ "fallback $name can be omitted in settings",+ ({ name }) => {+ expect(+ customResponseHeader.safeParse({ name, value: null }).success+ ).toBe(true);+ expect(+ projectMeta.safeParse({ customHeaders: [{ name, value: null }] })+ .success+ ).toBe(true);+ expect(hasCustomResponseHeaders([{ name, value: null }])).toBe(false);+ }+ );++ test.each([+ "X-Powered-By",+ "x-powered-by",+ "X-Content-Type-Options",+ "x-content-type-options",+ "Strict-Transport-Security",+ "strict-transport-security",+ ])("rejects dispatcher-owned header %j", (name) => {+ for (const value of ["value", null]) {+ expect(customResponseHeaders.safeParse([{ name, value }]).success).toBe(+ false+ );+ }+ });++ test.each(forbiddenCustomResponseHeaderNames)(+ "rejects forbidden custom response header %s, including case variants and removal rules",+ (name) => {+ for (const value of ["value", null]) {+ expect(customResponseHeader.safeParse({ name, value }).success).toBe(+ false+ );+ expect(+ customResponseHeader.safeParse({ name: name.toUpperCase(), value })+ .success+ ).toBe(false);+ }+ }+ );++ test.each(["", "Bad Header", "X:Test", "X-💥", "Content-Security-Policy\n"])(+ "rejects invalid header name %j",+ (name) => {+ expect(+ customResponseHeader.safeParse({ name, value: "value" }).success+ ).toBe(false);+ }+ );++ test.each([+ "",+ " \t ",+ "ok\r\nSet-Cookie: secret",+ "bad\nvalue",+ "bad\0value",+ "bad\x7fvalue",+ "💥",+ ])("rejects invalid header value %j", (value) => {+ expect(+ customResponseHeaders.safeParse([+ { name: "Content-Security-Policy", value },+ ]).success+ ).toBe(false);+ });++ test("rejects case-insensitive duplicates and excessive values", () => {+ expect(+ customResponseHeaders.safeParse([+ { name: "X-Frame-Options", value: "DENY" },+ { name: "x-frame-options", value: null },+ ]).success+ ).toBe(false);+ expect(+ customResponseHeaders.safeParse([+ { name: "Content-Security-Policy", value: "a".repeat(8193) },+ ]).success+ ).toBe(false);+ });+});diff --git a/packages/sdk/src/schema/response-headers.ts b/packages/sdk/src/schema/response-headers.tsnew file mode 100644index 0000000000..dad4f57aed--- /dev/null+++ b/packages/sdk/src/schema/response-headers.ts@@ -0,0 +1,138 @@+import { z } from "zod";+import { validateWsAuthRoute } from "@webstudio-is/wsauth";++// Keep fallback defaults in sync with the Cloud dispatcher.+export const responseHeaderDefinitions = [+ {+ name: "Content-Security-Policy",+ defaultValue: "frame-ancestors 'self'",+ },+ { name: "X-Frame-Options", defaultValue: "SAMEORIGIN" },+ {+ name: "Referrer-Policy",+ defaultValue: "strict-origin-when-cross-origin",+ },+] as const;++const platformHeaderNames = new Set([+ "x-powered-by",+ "x-content-type-options",+ "strict-transport-security",+]);++// Keep in sync with the published worker's forbiddenCustomResponseHeaderNames.+// Static route rules must not customize cookies, connection state, or values+// that describe the actual response body and status.+export const forbiddenCustomResponseHeaderNames = [+ "cookie",+ "cookie2",+ "set-cookie",+ "set-cookie2",+ "connection",+ "keep-alive",+ "proxy-connection",+ "te",+ "trailer",+ "transfer-encoding",+ "upgrade",+ "http2-settings",+ "content-length",+ "content-encoding",+ "content-range",+ "proxy-authenticate",+ "proxy-authentication-info",+] as const;++const forbiddenCustomHeaderNames = new Set<string>(+ forbiddenCustomResponseHeaderNames+);++export type ResponseHeaderDefinition =+ (typeof responseHeaderDefinitions)[number];++export const getResponseHeaderDefinition = (name: string) =>+ responseHeaderDefinitions.find(+ (header) => header.name.toLowerCase() === name.toLowerCase()+ );++export const customResponseHeader = z.object({+ // Omitted route is the site-wide setting used by existing projects.+ route: z+ .string()+ .max(2048)+ .refine(+ (route) => validateWsAuthRoute(route) === undefined,+ "Invalid route"+ )+ .optional(),+ name: z+ .string()+ .max(256, "Header name must be at most 256 characters")+ .refine(+ (name) => /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name),+ "Enter a valid HTTP header name"+ )+ .refine(+ (name) => !platformHeaderNames.has(name.toLowerCase()),+ "This header is managed by Webstudio Cloud"+ )+ .refine(+ (name) => !forbiddenCustomHeaderNames.has(name.toLowerCase()),+ "This response header cannot be customized"+ ),+ value: z+ .string()+ .max(8192, "Header value must be at most 8192 characters")+ // Unlike $ alone, the final assertion also rejects a trailing newline.+ .regex(+ /^[\t\x20-\x7e\x80-\xff]*$(?![\s\S])/,+ "Header values cannot contain newlines, control characters, or Unicode outside Latin-1"+ )+ .refine((value) => value.trim().length > 0, "Header value cannot be empty")+ .nullable(),+});++export const customResponseHeaders = z+ .array(customResponseHeader)+ .max(100, "At most 100 response header rules are supported")+ .superRefine((headers, context) => {+ const names = new Set<string>();+ let size = 0;+ for (const [index, header] of headers.entries()) {+ const name = `${header.route ?? "/*"}\0${header.name.toLowerCase()}`;+ if (names.has(name)) {+ context.addIssue({+ code: "custom",+ path: [index, "name"],+ message: "This header is already configured for this route",+ });+ }+ names.add(name);+ size +=+ (header.route?.length ?? 0) ++ header.name.length ++ (header.value?.length ?? 0) ++ 4;+ }+ if (size > 16384) {+ context.addIssue({+ code: "custom",+ message: "Response headers must total at most 16 KB",+ });+ }+ });++export type CustomResponseHeader = z.infer<typeof customResponseHeader>;++// Explicitly setting a fallback default is not a Pro customization.+export const hasCustomResponseHeaders = (+ headers: readonly CustomResponseHeader[] = []+) =>+ headers.some(({ route, name, value }) => {+ const definition = getResponseHeaderDefinition(name);+ return (+ (route !== undefined && route !== "/*") ||+ definition === undefined ||+ (value !== null && value?.trim() !== definition.defaultValue)+ );+ });