Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: Validate response headers and expose MCP rule edits (#6444)

Oleg Isonenbe74d8d69878
diff --git a/apps/builder/app/builder/features/publish/restricted-features.test.ts b/apps/builder/app/builder/features/publish/restricted-features.test.ts
index f788ab4292..3a902de7d4 100644
--- a/apps/builder/app/builder/features/publish/restricted-features.test.ts
+++ b/apps/builder/app/builder/features/publish/restricted-features.test.ts
@@ -172,7 +172,7 @@ describe("getRestrictedFeatures", () => {
name: "Content-Security-Policy",
value: "frame-ancestors https://example.com",
},
- { name: "X-Frame-Options", value: null },
+ { name: "X-Frame-Options", value: "DENY" },
],
},
},
@@ -185,11 +185,10 @@ describe("getRestrictedFeatures", () => {
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)",
+ "does not warn about missing or default custom headers (%j)",
(customHeaders) => {
const features = getFeatures({
pages: createPages(),
diff --git a/apps/builder/app/shared/project-settings/project-settings.stories.tsx b/apps/builder/app/shared/project-settings/project-settings.stories.tsx
index 36bf9e98fb..c6d41ca0ae 100644
--- a/apps/builder/app/shared/project-settings/project-settings.stories.tsx
+++ b/apps/builder/app/shared/project-settings/project-settings.stories.tsx
@@ -49,7 +49,7 @@ const HeadersStory = ({ customized = false }: { customized?: boolean }) => {
value:
"frame-ancestors 'self' https://example.com https://another-example.com",
},
- { name: "X-Frame-Options", value: null },
+ { name: "X-Frame-Options", value: "DENY" },
{
route: "/private/*",
name: "Referrer-Policy",
diff --git a/apps/builder/app/shared/project-settings/section-headers.test.tsx b/apps/builder/app/shared/project-settings/section-headers.test.tsx
index c6b4e1f960..f4a94403cb 100644
--- a/apps/builder/app/shared/project-settings/section-headers.test.tsx
+++ b/apps/builder/app/shared/project-settings/section-headers.test.tsx
@@ -362,14 +362,17 @@ test("shows an error when confirmed deletion cannot be saved", async () => {
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();
-});
+test.each(["Content-Security-Policy", "X-Custom-Header"])(
+ "empty route value cannot create a %s rule",
+ async (headerName) => {
+ executeRuntimeMutation.mockReturnValue({} as never);
+ const { route, name } = render();
+ await type(route, "/private/*");
+ await type(name, headerName);
+ 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.tsx
index 9fd9d499e0..d377357a71 100644
--- a/apps/builder/app/shared/project-settings/section-headers.tsx
+++ b/apps/builder/app/shared/project-settings/section-headers.tsx
@@ -1,5 +1,6 @@
import { useState } from "react";
import { useStore } from "@nanostores/react";
+import { ZodError } from "zod";
import {
Flex,
Grid,
@@ -13,8 +14,8 @@ import {
import { InfoCircleIcon } from "@webstudio-is/icons";
import {
customResponseHeader,
- customResponseHeaders,
- getResponseHeaderDefinition,
+ customResponseHeaderKey,
+ editCustomResponseHeaders,
type CustomResponseHeader,
} from "@webstudio-is/sdk";
import { validateWsAuthRoute } from "@webstudio-is/wsauth";
@@ -32,9 +33,6 @@ import {
} from "./response-header-suggestions";
import { getExistingRoutePaths, sectionSpacing } from "./utils";
-const ruleKey = (route: string, name: string) =>
- `${route}\0${name.toLowerCase()}`;
-
export const SectionHeaders = ({
executeMutation = executeRuntimeMutation,
}: {
@@ -54,18 +52,20 @@ export const SectionHeaders = ({
const save = (
next: CustomResponseHeader | undefined,
- previousKey?: string
+ 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) {
+ let headers: CustomResponseHeader[];
+ try {
+ headers = editCustomResponseHeaders(
+ $projectSettings.get()?.meta.customHeaders ?? [],
+ previousKey,
+ next
+ );
+ } catch (error) {
setSaveError(
- result.error.issues.map((issue) => issue.message).join(". ")
+ error instanceof ZodError
+ ? error.issues.map((issue) => issue.message).join(". ")
+ : "Invalid response header"
);
return false;
}
@@ -73,7 +73,7 @@ export const SectionHeaders = ({
const mutation = executeMutation({
id: "projectSettings.update",
input: {
- meta: { customHeaders: result.data.length ? result.data : null },
+ meta: { customHeaders: headers.length ? headers : null },
},
});
if (mutation !== undefined) {
@@ -165,16 +165,13 @@ export const SectionHeaders = ({
if (routeError) {
errors.route = [routeError];
}
- if (
- value === "" &&
- (route === "/*" || getResponseHeaderDefinition(name) !== undefined)
- ) {
+ if (value === "") {
errors.value = ["Enter a header value"];
}
const result = customResponseHeader.safeParse({
route,
name,
- value: value === "" ? null : value,
+ value,
});
if (!result.success) {
for (const issue of result.error.issues) {
@@ -186,25 +183,22 @@ export const SectionHeaders = ({
}}
onSubmit={(values) => {
const route = values.route.trim();
- const value = values.value?.trim();
+ const value = values.value?.trim() ?? "";
const name =
getResponseHeaderName(values.name.trim()) ?? values.name.trim();
const next: CustomResponseHeader = {
...(route === "/*" ? {} : { route }),
name,
- value: value || null,
+ value,
};
- return save(next, ruleKey(route, name));
+ return save(next, customResponseHeaderKey({ 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");
+ const key = customResponseHeaderKey(header);
return {
key,
values: [
@@ -214,8 +208,8 @@ export const SectionHeaders = ({
<Tooltip content={header.name} key="name">
<Text truncate>{header.name}</Text>
</Tooltip>,
- <Tooltip content={value} key="value">
- <Text truncate>{value}</Text>
+ <Tooltip content={header.value} key="value">
+ <Text truncate>{header.value}</Text>
</Tooltip>,
],
actions: (
diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.json
index f94dca7290..797d7f0fea 100644
--- a/fixtures/react-router-cloudflare/.webstudio/data.json
+++ b/fixtures/react-router-cloudflare/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1fx8bdt",
+ "bundleVersion": "bundle-1he6g9u",
"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.json
index f94dca7290..797d7f0fea 100644
--- a/fixtures/react-router-docker/.webstudio/data.json
+++ b/fixtures/react-router-docker/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1fx8bdt",
+ "bundleVersion": "bundle-1he6g9u",
"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.json
index f94dca7290..797d7f0fea 100644
--- a/fixtures/react-router-netlify/.webstudio/data.json
+++ b/fixtures/react-router-netlify/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1fx8bdt",
+ "bundleVersion": "bundle-1he6g9u",
"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.json
index f94dca7290..797d7f0fea 100644
--- a/fixtures/react-router-vercel/.webstudio/data.json
+++ b/fixtures/react-router-vercel/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1fx8bdt",
+ "bundleVersion": "bundle-1he6g9u",
"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.json
index 6199577c04..cb2cc8b4e6 100644
--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json
+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1fx8bdt",
+ "bundleVersion": "bundle-1he6g9u",
"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.json
index ab1b350348..7138a5d242 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-1fx8bdt",
+ "bundleVersion": "bundle-1he6g9u",
"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.json
index 6199577c04..cb2cc8b4e6 100644
--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json
+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1fx8bdt",
+ "bundleVersion": "bundle-1he6g9u",
"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.json
index 3b35bc85d0..2ed5f73d73 100644
--- a/fixtures/webstudio-features/.webstudio/data.json
+++ b/fixtures/webstudio-features/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1fx8bdt",
+ "bundleVersion": "bundle-1he6g9u",
"build": {
"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32",
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.ts
index 6e7cc31397..43a5670fa0 100644
--- a/packages/cli/src/commands/api-command-metadata.ts
+++ b/packages/cli/src/commands/api-command-metadata.ts
@@ -147,6 +147,9 @@ const apiCommandOptionsByCommand: Partial<
"submit-marketplace-product":
apiCommand.submitMarketplaceProductCommandOptions,
"list-redirects": apiCommand.paginatedListCommandOptions,
+ "list-response-headers": apiCommand.paginatedListCommandOptions,
+ "set-response-header": apiCommand.setResponseHeaderCommandOptions,
+ "delete-response-header": apiCommand.deleteResponseHeaderCommandOptions,
"create-redirect": apiCommand.createRedirectCommandOptions,
"update-redirect": apiCommand.updateRedirectCommandOptions,
"delete-redirect": apiCommand.deleteRedirectCommandOptions,
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index 4ce06f20ba..a71440796c 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -283,6 +283,27 @@ export const projectSettingsCommandOptions = (yargs: CommonYargsArgv) =>
export const paginatedListCommandOptions = (yargs: CommonYargsArgv) =>
outputDetailCommandOptions(apiCommandOptions(yargs));
+const responseHeaderCommandOptions = (yargs: CommonYargsArgv) =>
+ apiCommandOptions(yargs)
+ .option("route", {
+ type: "string",
+ describe: "Route pattern; omit for all paths",
+ })
+ .option("name", {
+ type: "string",
+ describe: "Response header name",
+ demandOption: true,
+ });
+
+export const setResponseHeaderCommandOptions = (yargs: CommonYargsArgv) =>
+ responseHeaderCommandOptions(yargs).option("value", {
+ type: "string",
+ describe: "Response header value",
+ demandOption: true,
+ });
+
+export const deleteResponseHeaderCommandOptions = responseHeaderCommandOptions;
+
export const updateProjectSettingsCommandOptions = (yargs: CommonYargsArgv) =>
requiredInputOption(
apiCommandOptions(yargs),
@@ -1342,6 +1363,7 @@ export type ApiCommandOptions = {
template?: string;
folder?: string;
path?: string;
+ route?: string;
name?: string;
variable?: string;
resource?: string;
@@ -2138,6 +2160,38 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
connection,
dependencies
),
+ "list-response-headers": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "list-response-headers",
+ {
+ cursor: options.cursor,
+ limit: options.limit,
+ verbose: options.verbose,
+ },
+ connection,
+ dependencies
+ ),
+ "set-response-header": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "set-response-header",
+ {
+ route: options.route,
+ name: requireOption(options.name, "--name"),
+ value: requireOption(options.value, "--value"),
+ },
+ connection,
+ dependencies
+ ),
+ "delete-response-header": async (options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "delete-response-header",
+ {
+ route: options.route,
+ name: requireOption(options.name, "--name"),
+ },
+ connection,
+ dependencies
+ ),
"create-redirect": async (options, connection, dependencies) => {
const input = {
old: requireOption(options.old, "--old"),
diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.ts
index 851503638a..bef957a81f 100644
--- a/packages/cli/src/commands/schema.test.ts
+++ b/packages/cli/src/commands/schema.test.ts
@@ -150,7 +150,7 @@ test("prints compact mcp tool summaries as json by default", () => {
})
);
// Includes the custom response headers schema in project settings updates.
- expect(JSON.stringify(handshakePayload).length).toBeLessThan(218_000);
+ expect(JSON.stringify(handshakePayload).length).toBeLessThan(220_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.ts
index d1528d07a7..ac35d878b5 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -796,7 +796,7 @@ describe("prebuild", () => {
name: "Content-Security-Policy",
value: "frame-ancestors https://example.com",
},
- { name: "X-Frame-Options", value: null },
+ { name: "X-Frame-Options", value: "DENY" },
],
},
compiler: {},
diff --git a/packages/cli/src/response-headers.ts b/packages/cli/src/response-headers.ts
index 66f008d785..74b4493572 100644
--- a/packages/cli/src/response-headers.ts
+++ b/packages/cli/src/response-headers.ts
@@ -6,7 +6,7 @@ export const generateResponseHeadersModule = (settings?: ProjectSettings) => {
settings?.meta.customHeaders ?? []
);
return `// Generated response header configuration for hosting adapters.
-export const customHeaders: Array<{ route?: string; name: string; value: string | null }> = ${JSON.stringify(
+export const customHeaders: Array<{ route?: string; name: string; value: string }> = ${JSON.stringify(
configured,
null,
2
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index ef450742f3..e5d9e88ec6 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -44,6 +44,7 @@ import {
deleteProps,
deleteResource,
deleteRedirect,
+ deleteResponseHeader,
deleteVariable,
duplicatePage,
duplicateAsset,
@@ -84,6 +85,7 @@ import {
listPageTemplates,
listPublishes,
listRedirects,
+ listResponseHeaders,
listResources,
listTexts,
listVariables,
@@ -115,6 +117,7 @@ import {
updateFolder,
updateProps,
updateProjectSettings,
+ setResponseHeader,
updateRedirect,
updateResource,
updateStyleDeclarations,
@@ -506,6 +509,18 @@ test("wraps project api trpc calls in named functions", async () => {
compiler: { atomicStyles: true },
});
await listRedirects(params);
+ await listResponseHeaders(params);
+ await setResponseHeader({
+ ...params,
+ route: "/docs/*",
+ name: "Cache-Control",
+ value: "public",
+ });
+ await deleteResponseHeader({
+ ...params,
+ route: "/docs/*",
+ name: "Cache-Control",
+ });
await createRedirect({
...params,
old: "/old",
@@ -931,6 +946,15 @@ test("wraps project api trpc calls in named functions", async () => {
expectRequest("/trpc/api.projectSettings.getMarketplaceProduct"),
expectBodyRequest("/trpc/api.projectSettings.update", '"siteName":"Acme"'),
expectRequest("/trpc/api.redirects.list"),
+ expectRequest("/trpc/api.responseHeaders.list"),
+ expectBodyRequest(
+ "/trpc/api.responseHeaders.set",
+ '"name":"Cache-Control"'
+ ),
+ expectBodyRequest(
+ "/trpc/api.responseHeaders.delete",
+ '"name":"Cache-Control"'
+ ),
expectBodyRequest("/trpc/api.redirects.create", '"old":"/old"'),
expectBodyRequest("/trpc/api.redirects.update", '"old":"/older"'),
expectBodyRequest("/trpc/api.redirects.delete", '"old":"/older"'),
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index 6b3f27b304..e4b8987d6d 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -4,6 +4,7 @@ import {
getAssetContentHash,
type AssetQueryResourceConfigurationInput,
type AssetFolder,
+ type CustomResponseHeader,
type ExpressionBindingMode,
} from "@webstudio-is/sdk";
import {
@@ -1638,6 +1639,7 @@ type ProjectSettingsInput = {
faviconAssetId?: string | null;
code?: string | null;
auth?: string | null;
+ customHeaders?: CustomResponseHeader[] | null;
};
compiler?: {
atomicStyles?: boolean | null;
@@ -1656,6 +1658,18 @@ export const listRedirects = projectQueryInput<
AuthProjectParams & PaginatedQueryInput
>("list-redirects");
+export const listResponseHeaders = projectQueryInput<
+ AuthProjectParams & PaginatedQueryInput
+>("list-response-headers");
+
+export const setResponseHeader = projectMutationInput<
+ AuthProjectParams & CustomResponseHeader
+>("set-response-header");
+
+export const deleteResponseHeader = projectMutationInput<
+ AuthProjectParams & Pick<CustomResponseHeader, "route" | "name">
+>("delete-response-header");
+
export const createRedirect = projectMutationInput<
AuthProjectParams & {
old: string;
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index ae105d3161..76fc6c9378 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -5418,18 +5418,13 @@ export const runtimeOperationContractData = [
name: {
type: "string",
maxLength: 256,
+ pattern: "^[!#$%&'*+.^_`|~0-9A-Za-z-]+$",
},
value: {
- anyOf: [
- {
- type: "string",
- maxLength: 8192,
- pattern: "^[\\t\\x20-\\x7e\\x80-\\xff]*$(?![\\s\\S])",
- },
- {
- type: "null",
- },
- ],
+ type: "string",
+ minLength: 1,
+ maxLength: 8192,
+ pattern: "^[\\t\\x20-\\x7e\\x80-\\xff]*$(?![\\s\\S])",
},
},
required: ["name", "value"],
@@ -5567,19 +5562,13 @@ export const runtimeOperationContractData = [
name: {
type: "string",
maxLength: 256,
+ pattern: "^[!#$%&'*+.^_`|~0-9A-Za-z-]+$",
},
value: {
- anyOf: [
- {
- type: "string",
- maxLength: 8192,
- pattern:
- "^[\\t\\x20-\\x7e\\x80-\\xff]*$(?![\\s\\S])",
- },
- {
- type: "null",
- },
- ],
+ type: "string",
+ minLength: 1,
+ maxLength: 8192,
+ pattern: "^[\\t\\x20-\\x7e\\x80-\\xff]*$(?![\\s\\S])",
},
},
required: ["name", "value"],
@@ -5632,6 +5621,180 @@ export const runtimeOperationContractData = [
invalidatesNamespaces: ["projectSettings"],
retryOnConflict: true,
},
+ {
+ id: "responseHeaders.list",
+ command: "list-response-headers",
+ client: "listResponseHeaders",
+ kind: "read",
+ inputSchema: {
+ type: "object",
+ properties: {
+ cursor: {
+ type: "string",
+ },
+ limit: {
+ type: "integer",
+ minimum: 1,
+ maximum: 200,
+ },
+ verbose: {
+ description:
+ "Expand the same result with complete records and diagnostics. Omit for compact output.",
+ type: "boolean",
+ },
+ },
+ required: [],
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ headers: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ route: {
+ type: "string",
+ maxLength: 2048,
+ },
+ name: {
+ type: "string",
+ maxLength: 256,
+ pattern: "^[!#$%&'*+.^_`|~0-9A-Za-z-]+$",
+ },
+ value: {
+ type: "string",
+ minLength: 1,
+ maxLength: 8192,
+ pattern: "^[\\t\\x20-\\x7e\\x80-\\xff]*$(?![\\s\\S])",
+ },
+ },
+ required: ["name", "value"],
+ },
+ },
+ detail: {
+ type: "string",
+ enum: ["compact", "verbose"],
+ },
+ total: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ returnedCount: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ nextCursor: {
+ anyOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "null",
+ },
+ ],
+ },
+ filters: {
+ type: "object",
+ properties: {},
+ additionalProperties: {},
+ required: [],
+ },
+ },
+ required: [
+ "headers",
+ "detail",
+ "total",
+ "returnedCount",
+ "nextCursor",
+ "filters",
+ ],
+ additionalProperties: {},
+ },
+ readNamespaces: ["projectSettings"],
+ writeNamespaces: [],
+ invalidatesNamespaces: [],
+ retryOnConflict: false,
+ },
+ {
+ id: "responseHeaders.set",
+ command: "set-response-header",
+ client: "setResponseHeader",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ route: {
+ type: "string",
+ maxLength: 2048,
+ },
+ name: {
+ type: "string",
+ maxLength: 256,
+ pattern: "^[!#$%&'*+.^_`|~0-9A-Za-z-]+$",
+ },
+ value: {
+ type: "string",
+ minLength: 1,
+ maxLength: 8192,
+ pattern: "^[\\t\\x20-\\x7e\\x80-\\xff]*$(?![\\s\\S])",
+ },
+ },
+ required: ["name", "value"],
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ updated: {
+ type: "boolean",
+ },
+ },
+ required: ["updated"],
+ additionalProperties: {},
+ },
+ readNamespaces: ["projectSettings"],
+ writeNamespaces: ["projectSettings"],
+ invalidatesNamespaces: ["projectSettings"],
+ retryOnConflict: true,
+ },
+ {
+ id: "responseHeaders.delete",
+ command: "delete-response-header",
+ client: "deleteResponseHeader",
+ kind: "mutation",
+ inputSchema: {
+ type: "object",
+ properties: {
+ route: {
+ type: "string",
+ maxLength: 2048,
+ },
+ name: {
+ type: "string",
+ maxLength: 256,
+ pattern: "^[!#$%&'*+.^_`|~0-9A-Za-z-]+$",
+ },
+ },
+ required: ["name"],
+ },
+ outputSchema: {
+ type: "object",
+ properties: {
+ updated: {
+ type: "boolean",
+ },
+ },
+ required: ["updated"],
+ additionalProperties: {},
+ },
+ readNamespaces: ["projectSettings"],
+ writeNamespaces: ["projectSettings"],
+ invalidatesNamespaces: ["projectSettings"],
+ retryOnConflict: true,
+ requiresConfirm: true,
+ },
{
id: "projectSettings.getMarketplaceProduct",
command: "get-marketplace-product",
diff --git a/packages/project-build/src/db/build.test.ts b/packages/project-build/src/db/build.test.ts
index 1846ea124b..83bc0fed17 100644
--- a/packages/project-build/src/db/build.test.ts
+++ b/packages/project-build/src/db/build.test.ts
@@ -384,14 +384,6 @@ describe("createProductionBuild (msw)", () => {
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,
@@ -522,12 +514,6 @@ describe("createProductionBuild (msw)", () => {
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 },
{
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index cebfe886ad..9037255e5e 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -815,6 +815,35 @@ describe("project session mcp adapter", () => {
]);
expect(toolNames).toContain("insert-fragment");
expect(toolNames).not.toContain("meta.get_more_tools");
+ const responseHeaderTools = listProjectSessionMcpTools(
+ runtimeOperationContracts
+ .filter(({ id }) => id.startsWith("responseHeaders."))
+ .map((contract) =>
+ publicOperation({
+ command: contract.command,
+ id: contract.id,
+ description: contract.command,
+ inputSchema: contract.inputSchema,
+ })
+ )
+ );
+ expect(responseHeaderTools.map(({ name }) => name)).toEqual(
+ expect.arrayContaining([
+ "list-response-headers",
+ "set-response-header",
+ "delete-response-header",
+ ])
+ );
+ expect(
+ responseHeaderTools.find(({ name }) => name === "set-response-header")
+ ?.inputSchema
+ ).toMatchObject({
+ required: ["name", "value"],
+ properties: {
+ name: { pattern: expect.any(String) },
+ value: { minLength: 1, pattern: expect.any(String) },
+ },
+ });
const assetOperationTools = listProjectSessionMcpTools(
runtimeOperationContracts
.filter(
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 5b16378da0..ce1cf3b0ac 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -4235,6 +4235,9 @@ const capabilityAreas = [
"update-page",
"get-project-settings",
"update-project-settings",
+ "list-response-headers",
+ "set-response-header",
+ "delete-response-header",
"list-redirects",
"create-redirect",
"update-redirect",
diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.ts
index ff8d713d13..7e967b8a82 100644
--- a/packages/project-build/src/runtime/cutover.ts
+++ b/packages/project-build/src/runtime/cutover.ts
@@ -50,6 +50,9 @@ export const builderRuntimeCutoverManifests = [
"projectSettings.getMarketplaceProduct",
"projectSettings.update",
"projectSettings.updateMarketplaceProduct",
+ "responseHeaders.list",
+ "responseHeaders.set",
+ "responseHeaders.delete",
] as const,
callers: ["appRouter.api.projectSettings"] as const,
},
diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.ts
index 614bc36104..bb11e5b265 100644
--- a/packages/project-build/src/runtime/output-schemas.ts
+++ b/packages/project-build/src/runtime/output-schemas.ts
@@ -3,6 +3,7 @@ import {
assetQueryWhereExpression,
assetType,
compilerSettings,
+ customResponseHeader,
dataSourceVariableValue,
documentTypes,
pageAuth,
@@ -426,6 +427,12 @@ export const runtimeOutputSchemas = {
redirects: z.array(redirect).optional(),
}),
"projectSettings.update": looseObject({ updated: z.boolean() }),
+ "responseHeaders.list": looseObject({
+ headers: z.array(customResponseHeader),
+ ...outputPage,
+ }),
+ "responseHeaders.set": looseObject({ updated: z.boolean() }),
+ "responseHeaders.delete": looseObject({ updated: z.boolean() }),
"projectSettings.getMarketplaceProduct": looseObject({
marketplaceProduct: looseObject(marketplaceProduct.shape).nullable(),
}),
diff --git a/packages/project-build/src/runtime/project-settings.test.ts b/packages/project-build/src/runtime/project-settings.test.ts
index e89439c4b6..c0a6f0c0fd 100644
--- a/packages/project-build/src/runtime/project-settings.test.ts
+++ b/packages/project-build/src/runtime/project-settings.test.ts
@@ -15,15 +15,18 @@ import {
createRedirect,
deleteBreakpoint,
deleteRedirect,
+ deleteResponseHeader,
getMarketplaceProduct,
getProjectSettings,
listBreakpoints,
listRedirects,
+ listResponseHeaders,
marketplaceProductUpdateInput,
projectSettingsUpdateInput,
redirectFieldsInput,
redirectUpdateFieldsInput,
setRedirects,
+ setResponseHeader,
updateBreakpoint,
updateMarketplaceProduct,
updateProjectSettings,
@@ -82,9 +85,50 @@ const context = {
};
describe("project settings runtime", () => {
+ test("MCP response-header operations use the same validation and route-specific edits", () => {
+ const state = createState();
+ const allPaths = { name: "Cache-Control", value: "public" };
+ expect(setResponseHeader(state, allPaths).payload[0]?.patches).toEqual([
+ { op: "add", path: ["meta", "customHeaders"], value: [allPaths] },
+ ]);
+ state.projectSettings!.meta.customHeaders = [allPaths];
+ expect(
+ setResponseHeader(state, {
+ route: "/",
+ name: "Cache-Control",
+ value: "private",
+ }).payload[0]?.patches
+ ).toEqual([
+ {
+ op: "replace",
+ path: ["meta", "customHeaders"],
+ value: [
+ { route: "/", name: "Cache-Control", value: "private" },
+ allPaths,
+ ],
+ },
+ ]);
+ state.projectSettings!.meta.customHeaders = [
+ { route: "/", name: "Cache-Control", value: "private" },
+ allPaths,
+ ];
+ expect(listResponseHeaders(state).headers).toEqual(
+ state.projectSettings!.meta.customHeaders
+ );
+ expect(
+ deleteResponseHeader(state, { name: "cache-control" }).payload[0]?.patches
+ ).toEqual([
+ {
+ op: "replace",
+ path: ["meta", "customHeaders"],
+ value: [{ route: "/", name: "Cache-Control", value: "private" }],
+ },
+ ]);
+ expect(() => deleteResponseHeader(state, { name: "Missing" })).toThrow();
+ });
test("saves custom headers and removes the configuration to restore defaults", () => {
const customHeaders = [
- { name: "X-Frame-Options", value: null },
+ { name: "X-Frame-Options", value: "DENY" },
{
name: "Content-Security-Policy",
value: "frame-ancestors https://example.com",
diff --git a/packages/project-build/src/runtime/project-settings.ts b/packages/project-build/src/runtime/project-settings.ts
index 5dcba7531b..4083ca6fe7 100644
--- a/packages/project-build/src/runtime/project-settings.ts
+++ b/packages/project-build/src/runtime/project-settings.ts
@@ -2,6 +2,9 @@ import type { Breakpoint, PageRedirect } from "@webstudio-is/sdk";
import {
breakpoint,
compilerSettings,
+ customResponseHeader,
+ customResponseHeaderKey,
+ editCustomResponseHeaders,
pageRedirect,
projectMeta,
projectNewRedirectPath,
@@ -240,6 +243,52 @@ export const updateProjectSettings = (
});
};
+export const listResponseHeaders = (
+ state: Pick<BuilderState, "projectSettings">,
+ input: PaginatedOutputInput = {}
+) => {
+ const { items, ...pagination } = paginateProjectSettingItems(
+ getRequiredProjectSettings(state).meta.customHeaders ?? [],
+ input
+ );
+ return { headers: items, ...pagination };
+};
+
+export const responseHeaderSetInput = customResponseHeader;
+export const responseHeaderDeleteInput = customResponseHeader.pick({
+ route: true,
+ name: true,
+});
+
+export const setResponseHeader = (
+ state: Pick<BuilderState, "projectSettings">,
+ input: z.infer<typeof responseHeaderSetInput>
+) => {
+ const headers = editCustomResponseHeaders(
+ getRequiredProjectSettings(state).meta.customHeaders ?? [],
+ customResponseHeaderKey(input),
+ input
+ );
+ return updateProjectSettings(state, {
+ meta: { customHeaders: headers },
+ });
+};
+
+export const deleteResponseHeader = (
+ state: Pick<BuilderState, "projectSettings">,
+ input: z.infer<typeof responseHeaderDeleteInput>
+) => {
+ const current = getRequiredProjectSettings(state).meta.customHeaders ?? [];
+ const key = customResponseHeaderKey(input);
+ if (current.every((header) => customResponseHeaderKey(header) !== key)) {
+ return throwBuilderRuntimeError("NOT_FOUND", "Response header not found");
+ }
+ const headers = editCustomResponseHeaders(current, key);
+ return updateProjectSettings(state, {
+ meta: { customHeaders: headers.length ? headers : null },
+ });
+};
+
export const updateMarketplaceProduct = (
_state: Pick<BuilderState, "marketplaceProduct">,
input: MarketplaceProduct
diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.ts
index c3f52f5158..e9a6c5f10d 100644
--- a/packages/project-build/src/runtime/registry.test.ts
+++ b/packages/project-build/src/runtime/registry.test.ts
@@ -2420,6 +2420,8 @@ describe("builder runtime registry", () => {
["pages.savePathInHistory", {}],
["pages.setHome", {}],
["projectSettings.update", { meta: "invalid" }],
+ ["responseHeaders.set", {}],
+ ["responseHeaders.delete", {}],
["projectSettings.updateMarketplaceProduct", {}],
["redirects.create", {}],
["redirects.update", {}],
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index bd64d563fe..dfa49ef91b 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -861,6 +861,35 @@ export const builderRuntimeOperations = [
projectSettings.projectSettingsUpdateInput,
({ state, input }) => projectSettings.updateProjectSettings(state, input)
),
+ runtimeOperation(
+ "responseHeaders.list",
+ api("list-response-headers", "listResponseHeaders"),
+ readContract(["projectSettings"]),
+ paginatedListInput,
+ ({ state, input }) => projectSettings.listResponseHeaders(state, input)
+ ),
+ runtimeOperation(
+ "responseHeaders.set",
+ api("set-response-header", "setResponseHeader"),
+ mutationContract({
+ readNamespaces: ["projectSettings"],
+ writeNamespaces: ["projectSettings"],
+ retryOnConflict: true,
+ }),
+ projectSettings.responseHeaderSetInput,
+ ({ state, input }) => projectSettings.setResponseHeader(state, input)
+ ),
+ runtimeOperation(
+ "responseHeaders.delete",
+ api("delete-response-header", "deleteResponseHeader"),
+ mutationContract({
+ readNamespaces: ["projectSettings"],
+ writeNamespaces: ["projectSettings"],
+ retryOnConflict: true,
+ }),
+ projectSettings.responseHeaderDeleteInput,
+ ({ state, input }) => projectSettings.deleteResponseHeader(state, input)
+ ),
runtimeOperation(
"projectSettings.getMarketplaceProduct",
api("get-marketplace-product", "getMarketplaceProduct"),
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index 31dd77d2af..2c09316687 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -115,6 +115,27 @@ const curatedPublicApiOperationDocumentation = [
description: "List project redirects",
examples: ["webstudio list-redirects --json"],
},
+ {
+ command: "list-response-headers",
+ description: "List configured response header rules",
+ examples: ["webstudio list-response-headers --json"],
+ },
+ {
+ command: "set-response-header",
+ description:
+ "Add or replace a response header for a route. Omit route for all paths.",
+ requiredOptions: ["name", "value", "json"],
+ examples: [
+ "webstudio set-response-header --name Cache-Control --value 'public, max-age=60' --json",
+ ],
+ },
+ {
+ command: "delete-response-header",
+ description:
+ "Delete a response header for a route. Omit route for the all-paths rule.",
+ requiredOptions: ["name", "json"],
+ examples: ["webstudio delete-response-header --name Cache-Control --json"],
+ },
{
command: "create-redirect",
description: "Create a project redirect",
diff --git a/packages/sdk/src/schema/response-headers.test.ts b/packages/sdk/src/schema/response-headers.test.ts
index 4096903d15..1597afcbd6 100644
--- a/packages/sdk/src/schema/response-headers.test.ts
+++ b/packages/sdk/src/schema/response-headers.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, test } from "vitest";
import { projectMeta } from "./pages";
import {
customResponseHeader,
+ customResponseHeaderKey,
customResponseHeaders,
+ editCustomResponseHeaders,
hasCustomResponseHeaders,
responseHeaderDefinitions,
forbiddenCustomResponseHeaderNames,
@@ -48,19 +50,42 @@ describe("response header settings", () => {
).toBe(false);
});
- test.each(responseHeaderDefinitions)(
- "fallback $name can be omitted in settings",
- ({ name }) => {
- expect(
- customResponseHeader.safeParse({ name, value: null }).success
- ).toBe(true);
+ test("edits rules by route and case-insensitive name", () => {
+ const headers = [
+ { name: "Cache-Control", value: "all paths" },
+ { route: "/", name: "Cache-Control", value: "root only" },
+ ];
+ const updated = editCustomResponseHeaders(
+ headers,
+ customResponseHeaderKey({ name: "cache-control" }),
+ { name: "cache-control", value: "updated" }
+ );
+ expect(updated).toEqual([
+ { name: "cache-control", value: "updated" },
+ headers[1],
+ ]);
+ expect(
+ editCustomResponseHeaders(
+ updated,
+ customResponseHeaderKey({ route: "/", name: "CACHE-CONTROL" })
+ )
+ ).toEqual([{ name: "cache-control", value: "updated" }]);
+ expect(() =>
+ editCustomResponseHeaders(headers, customResponseHeaderKey(headers[0]), {
+ name: "Set-Cookie",
+ value: "session=secret",
+ })
+ ).toThrow();
+ });
+
+ test("a rule requires a nonempty string value", () => {
+ for (const value of [null, "", " "]) {
expect(
- projectMeta.safeParse({ customHeaders: [{ name, value: null }] })
+ customResponseHeader.safeParse({ name: "X-Frame-Options", value })
.success
- ).toBe(true);
- expect(hasCustomResponseHeaders([{ name, value: null }])).toBe(false);
+ ).toBe(false);
}
- );
+ });
test.each([
"X-Powered-By",
@@ -70,25 +95,23 @@ describe("response header settings", () => {
"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
- );
- }
+ expect(
+ customResponseHeaders.safeParse([{ name, value: "value" }]).success
+ ).toBe(false);
});
test.each(forbiddenCustomResponseHeaderNames)(
- "rejects forbidden custom response header %s, including case variants and removal rules",
+ "rejects forbidden custom response header %s, including case variants",
(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);
- }
+ expect(
+ customResponseHeader.safeParse({ name, value: "value" }).success
+ ).toBe(false);
+ expect(
+ customResponseHeader.safeParse({
+ name: name.toUpperCase(),
+ value: "value",
+ }).success
+ ).toBe(false);
}
);
@@ -121,7 +144,7 @@ describe("response header settings", () => {
expect(
customResponseHeaders.safeParse([
{ name: "X-Frame-Options", value: "DENY" },
- { name: "x-frame-options", value: null },
+ { name: "x-frame-options", value: "SAMEORIGIN" },
]).success
).toBe(false);
expect(
diff --git a/packages/sdk/src/schema/response-headers.ts b/packages/sdk/src/schema/response-headers.ts
index dad4f57aed..1e2011aa35 100644
--- a/packages/sdk/src/schema/response-headers.ts
+++ b/packages/sdk/src/schema/response-headers.ts
@@ -20,7 +20,6 @@ const platformHeaderNames = new Set([
"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 = [
@@ -68,10 +67,7 @@ export const customResponseHeader = z.object({
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"
- )
+ .regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/, "Enter a valid HTTP header name")
.refine(
(name) => !platformHeaderNames.has(name.toLowerCase()),
"This header is managed by Webstudio Cloud"
@@ -82,14 +78,14 @@ export const customResponseHeader = z.object({
),
value: z
.string()
+ .min(1, "Header value cannot be empty")
.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(),
+ .refine((value) => value.trim().length > 0, "Header value cannot be empty"),
});
export const customResponseHeaders = z
@@ -111,7 +107,7 @@ export const customResponseHeaders = z
size +=
(header.route?.length ?? 0) +
header.name.length +
- (header.value?.length ?? 0) +
+ header.value.length +
4;
}
if (size > 16384) {
@@ -124,6 +120,26 @@ export const customResponseHeaders = z
export type CustomResponseHeader = z.infer<typeof customResponseHeader>;
+export const customResponseHeaderKey = ({
+ route,
+ name,
+}: Pick<CustomResponseHeader, "route" | "name">) =>
+ `${route ?? "/*"}\0${name.toLowerCase()}`;
+
+export const editCustomResponseHeaders = (
+ headers: readonly CustomResponseHeader[],
+ key: string,
+ next?: CustomResponseHeader
+) => {
+ const updated = headers.filter(
+ (header) => customResponseHeaderKey(header) !== key
+ );
+ if (next !== undefined) {
+ updated.unshift(next);
+ }
+ return customResponseHeaders.parse(updated);
+};
+
// Explicitly setting a fallback default is not a Pro customization.
export const hasCustomResponseHeaders = (
headers: readonly CustomResponseHeader[] = []
@@ -133,6 +149,6 @@ export const hasCustomResponseHeaders = (
return (
(route !== undefined && route !== "/*") ||
definition === undefined ||
- (value !== null && value?.trim() !== definition.defaultValue)
+ value.trim() !== definition.defaultValue
);
});