red-design-mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,277 @@
1
+ // Parses the CSS color syntaxes people actually write. Self-contained on purpose (no imports).
2
+ export const SUPPORTED_COLOR_FORMATS = "hex (#rgb, #rrggbb, #rrggbbaa), rgb(), hsl(), hwb(), oklch(), oklab() or a CSS color name";
3
+ const NAMED = {
4
+ aliceblue: "#f0f8ff",
5
+ antiquewhite: "#faebd7",
6
+ aqua: "#00ffff",
7
+ aquamarine: "#7fffd4",
8
+ azure: "#f0ffff",
9
+ beige: "#f5f5dc",
10
+ bisque: "#ffe4c4",
11
+ black: "#000000",
12
+ blanchedalmond: "#ffebcd",
13
+ blue: "#0000ff",
14
+ blueviolet: "#8a2be2",
15
+ brown: "#a52a2a",
16
+ burlywood: "#deb887",
17
+ cadetblue: "#5f9ea0",
18
+ chartreuse: "#7fff00",
19
+ chocolate: "#d2691e",
20
+ coral: "#ff7f50",
21
+ cornflowerblue: "#6495ed",
22
+ cornsilk: "#fff8dc",
23
+ crimson: "#dc143c",
24
+ cyan: "#00ffff",
25
+ darkblue: "#00008b",
26
+ darkcyan: "#008b8b",
27
+ darkgoldenrod: "#b8860b",
28
+ darkgray: "#a9a9a9",
29
+ darkgreen: "#006400",
30
+ darkgrey: "#a9a9a9",
31
+ darkkhaki: "#bdb76b",
32
+ darkmagenta: "#8b008b",
33
+ darkolivegreen: "#556b2f",
34
+ darkorange: "#ff8c00",
35
+ darkorchid: "#9932cc",
36
+ darkred: "#8b0000",
37
+ darksalmon: "#e9967a",
38
+ darkseagreen: "#8fbc8f",
39
+ darkslateblue: "#483d8b",
40
+ darkslategray: "#2f4f4f",
41
+ darkslategrey: "#2f4f4f",
42
+ darkturquoise: "#00ced1",
43
+ darkviolet: "#9400d3",
44
+ deeppink: "#ff1493",
45
+ deepskyblue: "#00bfff",
46
+ dimgray: "#696969",
47
+ dimgrey: "#696969",
48
+ dodgerblue: "#1e90ff",
49
+ firebrick: "#b22222",
50
+ floralwhite: "#fffaf0",
51
+ forestgreen: "#228b22",
52
+ fuchsia: "#ff00ff",
53
+ gainsboro: "#dcdcdc",
54
+ ghostwhite: "#f8f8ff",
55
+ gold: "#ffd700",
56
+ goldenrod: "#daa520",
57
+ gray: "#808080",
58
+ green: "#008000",
59
+ greenyellow: "#adff2f",
60
+ grey: "#808080",
61
+ honeydew: "#f0fff0",
62
+ hotpink: "#ff69b4",
63
+ indianred: "#cd5c5c",
64
+ indigo: "#4b0082",
65
+ ivory: "#fffff0",
66
+ khaki: "#f0e68c",
67
+ lavender: "#e6e6fa",
68
+ lavenderblush: "#fff0f5",
69
+ lawngreen: "#7cfc00",
70
+ lemonchiffon: "#fffacd",
71
+ lightblue: "#add8e6",
72
+ lightcoral: "#f08080",
73
+ lightcyan: "#e0ffff",
74
+ lightgoldenrodyellow: "#fafad2",
75
+ lightgray: "#d3d3d3",
76
+ lightgreen: "#90ee90",
77
+ lightgrey: "#d3d3d3",
78
+ lightpink: "#ffb6c1",
79
+ lightsalmon: "#ffa07a",
80
+ lightseagreen: "#20b2aa",
81
+ lightskyblue: "#87cefa",
82
+ lightslategray: "#778899",
83
+ lightslategrey: "#778899",
84
+ lightsteelblue: "#b0c4de",
85
+ lightyellow: "#ffffe0",
86
+ lime: "#00ff00",
87
+ limegreen: "#32cd32",
88
+ linen: "#faf0e6",
89
+ magenta: "#ff00ff",
90
+ maroon: "#800000",
91
+ mediumaquamarine: "#66cdaa",
92
+ mediumblue: "#0000cd",
93
+ mediumorchid: "#ba55d3",
94
+ mediumpurple: "#9370db",
95
+ mediumseagreen: "#3cb371",
96
+ mediumslateblue: "#7b68ee",
97
+ mediumspringgreen: "#00fa9a",
98
+ mediumturquoise: "#48d1cc",
99
+ mediumvioletred: "#c71585",
100
+ midnightblue: "#191970",
101
+ mintcream: "#f5fffa",
102
+ mistyrose: "#ffe4e1",
103
+ moccasin: "#ffe4b5",
104
+ navajowhite: "#ffdead",
105
+ navy: "#000080",
106
+ oldlace: "#fdf5e6",
107
+ olive: "#808000",
108
+ olivedrab: "#6b8e23",
109
+ orange: "#ffa500",
110
+ orangered: "#ff4500",
111
+ orchid: "#da70d6",
112
+ palegoldenrod: "#eee8aa",
113
+ palegreen: "#98fb98",
114
+ paleturquoise: "#afeeee",
115
+ palevioletred: "#db7093",
116
+ papayawhip: "#ffefd5",
117
+ peachpuff: "#ffdab9",
118
+ peru: "#cd853f",
119
+ pink: "#ffc0cb",
120
+ plum: "#dda0dd",
121
+ powderblue: "#b0e0e6",
122
+ purple: "#800080",
123
+ rebeccapurple: "#663399",
124
+ red: "#ff0000",
125
+ rosybrown: "#bc8f8f",
126
+ royalblue: "#4169e1",
127
+ saddlebrown: "#8b4513",
128
+ salmon: "#fa8072",
129
+ sandybrown: "#f4a460",
130
+ seagreen: "#2e8b57",
131
+ seashell: "#fff5ee",
132
+ sienna: "#a0522d",
133
+ silver: "#c0c0c0",
134
+ skyblue: "#87ceeb",
135
+ slateblue: "#6a5acd",
136
+ slategray: "#708090",
137
+ slategrey: "#708090",
138
+ snow: "#fffafa",
139
+ springgreen: "#00ff7f",
140
+ steelblue: "#4682b4",
141
+ tan: "#d2b48c",
142
+ teal: "#008080",
143
+ thistle: "#d8bfd8",
144
+ tomato: "#ff6347",
145
+ turquoise: "#40e0d0",
146
+ violet: "#ee82ee",
147
+ wheat: "#f5deb3",
148
+ white: "#ffffff",
149
+ whitesmoke: "#f5f5f5",
150
+ yellow: "#ffff00",
151
+ yellowgreen: "#9acd32"
152
+ };
153
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
154
+ const round = (rgb) => rgb.map((v) => Math.round(clamp(v, 0, 255)));
155
+ function hslToRgb(h0, s, l) {
156
+ const h = ((h0 % 360) + 360) % 360;
157
+ const c = (1 - Math.abs(2 * l - 1)) * s;
158
+ const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
159
+ const m = l - c / 2;
160
+ const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x];
161
+ return [(r + m) * 255, (g + m) * 255, (b + m) * 255];
162
+ }
163
+ const toSrgb = (c) => {
164
+ const v = clamp(c, 0, 1);
165
+ return 255 * (v <= 0.0031308 ? 12.92 * v : 1.055 * Math.pow(v, 1 / 2.4) - 0.055);
166
+ };
167
+ function oklabToRgb(L, a, b) {
168
+ const l = Math.pow(L + 0.3963377774 * a + 0.2158037573 * b, 3);
169
+ const m = Math.pow(L - 0.1055613458 * a - 0.0638541728 * b, 3);
170
+ const s = Math.pow(L - 0.0894841775 * a - 1.291485548 * b, 3);
171
+ return [
172
+ toSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
173
+ toSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
174
+ toSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
175
+ ];
176
+ }
177
+ /** A number, or a percentage of `scale`. "none" counts as 0. */
178
+ function num(tok, scale) {
179
+ if (tok === undefined)
180
+ return null;
181
+ if (tok === "none")
182
+ return 0;
183
+ const m = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(%?)$/i.exec(tok);
184
+ if (!m)
185
+ return null;
186
+ const v = parseFloat(m[1]);
187
+ return m[2] ? (v / 100) * scale : v;
188
+ }
189
+ function hue(tok) {
190
+ if (tok === undefined)
191
+ return null;
192
+ if (tok === "none")
193
+ return 0;
194
+ const m = /^([+-]?(?:\d+\.?\d*|\.\d+))(deg|grad|rad|turn)?$/i.exec(tok);
195
+ if (!m)
196
+ return null;
197
+ const v = parseFloat(m[1]);
198
+ const u = (m[2] ?? "deg").toLowerCase();
199
+ return u === "turn" ? v * 360 : u === "grad" ? v * 0.9 : u === "rad" ? (v * 180) / Math.PI : v;
200
+ }
201
+ function fromFunction(name, body) {
202
+ let main = body;
203
+ let alphaTok;
204
+ const slash = body.indexOf("/");
205
+ if (slash !== -1) {
206
+ main = body.slice(0, slash);
207
+ alphaTok = body.slice(slash + 1).trim();
208
+ }
209
+ const t = main.trim().split(/[\s,]+/).filter(Boolean);
210
+ if (slash === -1 && t.length === 4)
211
+ alphaTok = t.pop();
212
+ if (t.length !== 3)
213
+ return null;
214
+ let alpha = 1;
215
+ if (alphaTok !== undefined) {
216
+ const a = num(alphaTok, 1);
217
+ if (a === null)
218
+ return null;
219
+ alpha = clamp(a, 0, 1);
220
+ }
221
+ let rgb = null;
222
+ if (name === "rgb" || name === "rgba") {
223
+ const v = t.map((x) => num(x, 255));
224
+ if (v.some((x) => x === null))
225
+ return null;
226
+ rgb = v;
227
+ }
228
+ else if (name === "hsl" || name === "hsla") {
229
+ const h = hue(t[0]), s = num(t[1], 1), l = num(t[2], 1);
230
+ if (h === null || s === null || l === null)
231
+ return null;
232
+ rgb = hslToRgb(h, clamp(s, 0, 1), clamp(l, 0, 1));
233
+ }
234
+ else if (name === "hwb") {
235
+ const h = hue(t[0]), w = num(t[1], 1), b = num(t[2], 1);
236
+ if (h === null || w === null || b === null)
237
+ return null;
238
+ const sum = w + b;
239
+ const [ww, bb] = sum > 1 ? [w / sum, b / sum] : [w, b];
240
+ rgb = hslToRgb(h, 1, 0.5).map((c) => (c / 255) * (1 - ww - bb) * 255 + ww * 255);
241
+ }
242
+ else if (name === "oklch") {
243
+ const L = num(t[0], 1), C = num(t[1], 0.4), h = hue(t[2]);
244
+ if (L === null || C === null || h === null)
245
+ return null;
246
+ const rad = (h * Math.PI) / 180;
247
+ rgb = oklabToRgb(L, C * Math.cos(rad), C * Math.sin(rad));
248
+ }
249
+ else if (name === "oklab") {
250
+ const L = num(t[0], 1), a = num(t[1], 0.4), b = num(t[2], 0.4);
251
+ if (L === null || a === null || b === null)
252
+ return null;
253
+ rgb = oklabToRgb(L, a, b);
254
+ }
255
+ return rgb ? { rgb: round(rgb), alpha } : null;
256
+ }
257
+ export function parseColor(input) {
258
+ if (typeof input !== "string")
259
+ return null;
260
+ const s = input.trim().toLowerCase();
261
+ if (!s)
262
+ return null;
263
+ const hex = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(s);
264
+ if (hex && (s.startsWith("#") || hex[1].length === 3 || hex[1].length === 6)) {
265
+ let h = hex[1];
266
+ if (h.length <= 4)
267
+ h = h.split("").map((c) => c + c).join("");
268
+ const n = (i) => parseInt(h.slice(i, i + 2), 16);
269
+ return { rgb: [n(0), n(2), n(4)], alpha: h.length === 8 ? n(6) / 255 : 1 };
270
+ }
271
+ if (s === "transparent")
272
+ return { rgb: [0, 0, 0], alpha: 0 };
273
+ if (NAMED[s])
274
+ return parseColor(NAMED[s]);
275
+ const fn = /^(rgba?|hsla?|hwb|oklch|oklab)\(\s*([^()]*?)\s*\)$/.exec(s);
276
+ return fn ? fromFunction(fn[1], fn[2]) : null;
277
+ }
package/dist/csp.js ADDED
@@ -0,0 +1,242 @@
1
+ import { createHash } from "node:crypto";
2
+ import { parseHtml } from "./htmlscan.js";
3
+ const sha256 = (s) => `'sha256-${createHash("sha256").update(s, "utf8").digest("base64")}'`;
4
+ const preview = (s) => s.replace(/\s+/g, " ").trim().slice(0, 48);
5
+ const EXECUTABLE = new Set(["", "text/javascript", "application/javascript", "module", "text/ecmascript", "application/ecmascript"]);
6
+ export function generateCsp(html, opts = {}) {
7
+ const p = parseHtml(html);
8
+ const base = opts.pageUrl ?? "https://page.invalid/";
9
+ let pageOrigin;
10
+ try {
11
+ pageOrigin = new URL(base).origin;
12
+ }
13
+ catch {
14
+ throw new Error(`"${opts.pageUrl}" is not a valid URL.`);
15
+ }
16
+ const https = new URL(base).protocol === "https:";
17
+ const source = (raw) => {
18
+ if (!raw)
19
+ return null;
20
+ const v = raw.trim();
21
+ if (!v || v.startsWith("#") || /^(javascript|mailto|tel|about|blob):/i.test(v))
22
+ return null;
23
+ if (/^data:/i.test(v))
24
+ return "data:";
25
+ try {
26
+ const u = new URL(v.startsWith("//") ? "https:" + v : v, base);
27
+ if (u.protocol !== "http:" && u.protocol !== "https:")
28
+ return null;
29
+ return u.origin === pageOrigin ? "'self'" : u.origin;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ };
35
+ const srcsetUrls = (s) => (s ?? "").split(",").map((x) => x.trim().split(/\s+/)[0]).filter(Boolean);
36
+ const d = {
37
+ "script-src": new Set(["'self'"]), "style-src": new Set(["'self'"]), "img-src": new Set(["'self'"]),
38
+ "font-src": new Set(["'self'"]), "connect-src": new Set(["'self'"]), "media-src": new Set(["'self'"]),
39
+ "frame-src": new Set(), "object-src": new Set(), "form-action": new Set(["'self'"]),
40
+ };
41
+ const add = (dir, raw) => {
42
+ const s = source(raw);
43
+ if (s)
44
+ d[dir].add(s);
45
+ };
46
+ let hasMedia = false, hasObject = false, styleAttrs = 0, handlers = 0, googleFonts = false;
47
+ for (const t of p.tags) {
48
+ for (const a of Object.keys(t.attrs))
49
+ if (/^on[a-z]+$/.test(a))
50
+ handlers++;
51
+ if ("style" in t.attrs)
52
+ styleAttrs++;
53
+ const rel = (t.attrs.rel ?? "").toLowerCase();
54
+ switch (t.name) {
55
+ case "script":
56
+ add("script-src", t.attrs.src);
57
+ break;
58
+ case "link":
59
+ if (rel.includes("stylesheet")) {
60
+ add("style-src", t.attrs.href);
61
+ if (/fonts\.googleapis\.com/i.test(t.attrs.href ?? ""))
62
+ googleFonts = true;
63
+ }
64
+ else if (rel.includes("preload") || rel.includes("prefetch")) {
65
+ const as = (t.attrs.as ?? "").toLowerCase();
66
+ add(as === "font" ? "font-src" : as === "style" ? "style-src" : as === "script" ? "script-src" : as === "image" ? "img-src" : "connect-src", t.attrs.href);
67
+ }
68
+ else if (rel.includes("icon"))
69
+ add("img-src", t.attrs.href);
70
+ break;
71
+ case "img":
72
+ add("img-src", t.attrs.src);
73
+ srcsetUrls(t.attrs.srcset).forEach((u) => add("img-src", u));
74
+ break;
75
+ case "source":
76
+ if (t.attrs.srcset)
77
+ srcsetUrls(t.attrs.srcset).forEach((u) => add("img-src", u));
78
+ else {
79
+ hasMedia = true;
80
+ add("media-src", t.attrs.src);
81
+ }
82
+ break;
83
+ case "video":
84
+ case "audio":
85
+ hasMedia = true;
86
+ add("media-src", t.attrs.src);
87
+ add("img-src", t.attrs.poster);
88
+ break;
89
+ case "iframe":
90
+ add("frame-src", t.attrs.src);
91
+ break;
92
+ case "object":
93
+ hasObject = true;
94
+ add("object-src", t.attrs.data);
95
+ break;
96
+ case "embed":
97
+ hasObject = true;
98
+ add("object-src", t.attrs.src);
99
+ break;
100
+ case "form":
101
+ add("form-action", t.attrs.action);
102
+ break;
103
+ }
104
+ }
105
+ if (googleFonts)
106
+ d["font-src"].add("https://fonts.gstatic.com");
107
+ const hashes = { script: [], style: [] };
108
+ for (const s of p.scripts) {
109
+ if (s.attrs.src || !EXECUTABLE.has((s.attrs.type ?? "").toLowerCase()) || !s.content.trim())
110
+ continue;
111
+ hashes.script.push({ hash: sha256(s.content), preview: preview(s.content) });
112
+ }
113
+ for (const s of p.styles)
114
+ if (s.content.trim())
115
+ hashes.style.push({ hash: sha256(s.content), preview: preview(s.content) });
116
+ hashes.script.forEach((h) => d["script-src"].add(h.hash));
117
+ hashes.style.forEach((h) => d["style-src"].add(h.hash));
118
+ const order = (set) => [...set].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
119
+ const rank = (v) => (v === "'self'" ? 0 : v.startsWith("'sha256-") ? 3 : v.endsWith(":") ? 2 : 1);
120
+ const directives = { "default-src": ["'self'"] };
121
+ directives["script-src"] = order(d["script-src"]);
122
+ directives["style-src"] = order(d["style-src"]);
123
+ if (styleAttrs && opts.allowInlineStyleAttributes !== false)
124
+ directives["style-src-attr"] = ["'unsafe-inline'"];
125
+ directives["img-src"] = order(d["img-src"]);
126
+ directives["font-src"] = order(d["font-src"]);
127
+ directives["connect-src"] = order(d["connect-src"]);
128
+ if (hasMedia)
129
+ directives["media-src"] = order(d["media-src"]);
130
+ directives["frame-src"] = d["frame-src"].size ? order(d["frame-src"]) : ["'none'"];
131
+ directives["object-src"] = hasObject && d["object-src"].size ? order(d["object-src"]) : ["'none'"];
132
+ directives["base-uri"] = ["'self'"];
133
+ directives["form-action"] = order(d["form-action"]);
134
+ directives["frame-ancestors"] = ["'self'"];
135
+ if (https)
136
+ directives["upgrade-insecure-requests"] = [];
137
+ const header = Object.entries(directives).map(([k, v]) => [k, ...v].join(" ")).join("; ");
138
+ const reportOnly = (opts.mode ?? "report-only") === "report-only";
139
+ const notes = [
140
+ "Only resources written in the HTML are known. Scripts, fonts and data that JavaScript loads later (APIs, analytics, widgets) are not, so add them to the matching directive (usually connect-src) when the browser console reports a violation.",
141
+ reportOnly ? "This is a report-only policy: nothing is blocked. Browse the site, fix the console reports, then switch to enforcement." : "This policy will block anything it does not list. Test every page first, ideally in report-only mode.",
142
+ ];
143
+ if (hashes.script.length || hashes.style.length)
144
+ notes.push("Hashes only match the exact inline text. Changing a single character, or a build step that rewrites the block, means the hash must be regenerated. For server-rendered pages, per-request nonces are sturdier.");
145
+ if (handlers)
146
+ notes.push(`${handlers} inline event handler${handlers > 1 ? "s (onclick and similar) are" : " (onclick or similar) is"} blocked by this policy. Replace ${handlers > 1 ? "them" : "it"} with addEventListener in a script file.`);
147
+ if (styleAttrs && opts.allowInlineStyleAttributes === false)
148
+ notes.push(`${styleAttrs} style="" attribute${styleAttrs > 1 ? "s are" : " is"} blocked. Move them into a stylesheet.`);
149
+ if (styleAttrs && opts.allowInlineStyleAttributes !== false)
150
+ notes.push(`${styleAttrs} style="" attribute${styleAttrs > 1 ? "s" : ""} allowed through style-src-attr 'unsafe-inline' (modern browsers). Moving them into stylesheets would let you drop it.`);
151
+ if (!opts.pageUrl)
152
+ notes.push("No page URL was given, so every absolute URL counts as another origin and relative URLs count as 'self'.");
153
+ return { headerName: reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy", header, directives, hashes, notes };
154
+ }
155
+ export function formatCsp(r) {
156
+ const fence = "`".repeat(3);
157
+ const lines = [
158
+ "## Content-Security-Policy",
159
+ `${fence}http`,
160
+ `${r.headerName}: ${r.header}`,
161
+ fence,
162
+ "",
163
+ "### Directives",
164
+ ...Object.entries(r.directives).map(([k, v]) => `- \`${k}\`: ${v.length ? v.map((x) => `\`${x}\``).join(" ") : "(flag, no value)"}`),
165
+ ];
166
+ const hs = [...r.hashes.script.map((h) => ({ ...h, kind: "script" })), ...r.hashes.style.map((h) => ({ ...h, kind: "style" }))];
167
+ if (hs.length)
168
+ lines.push("", "### Inline blocks allowed by hash", ...hs.map((h) => `- ${h.kind}: \`${h.preview}\` → \`${h.hash}\``));
169
+ lines.push("", "### Before you ship it", ...r.notes.map((n) => `- ${n}`));
170
+ return lines.join("\n");
171
+ }
172
+ /* ---------------------------- Security header files ---------------------------- */
173
+ export const HEADER_PLATFORMS = ["netlify", "cloudflare-pages", "vercel", "nginx", "apache", "caddy", "express"];
174
+ export function securityHeaderList(o = {}) {
175
+ const list = [
176
+ ["Strict-Transport-Security", `max-age=31536000; includeSubDomains${o.hstsPreload ? "; preload" : ""}`],
177
+ ["X-Content-Type-Options", "nosniff"],
178
+ ["X-Frame-Options", (o.frame ?? "deny").toUpperCase()],
179
+ ["Referrer-Policy", "strict-origin-when-cross-origin"],
180
+ ["Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()"],
181
+ ["Cross-Origin-Opener-Policy", "same-origin"],
182
+ ];
183
+ if (o.isolateCrossOrigin)
184
+ list.push(["Cross-Origin-Resource-Policy", "same-site"]);
185
+ if (o.csp) {
186
+ if (o.csp.length > 4000 || !/^[\x20-\x7E]+$/.test(o.csp) || /["\\$`]/.test(o.csp)) {
187
+ throw new Error('The CSP must be one line of printable ASCII, at most 4000 characters, without double quotes, backslashes, "$" or backticks (they could break out of the config file).');
188
+ }
189
+ list.push([(o.cspMode ?? "report-only") === "report-only" ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy", o.csp]);
190
+ }
191
+ return list;
192
+ }
193
+ export function generateSecurityHeaders(platform, o = {}) {
194
+ const hs = securityHeaderList(o);
195
+ let config;
196
+ let filename;
197
+ switch (platform) {
198
+ case "netlify":
199
+ case "cloudflare-pages":
200
+ filename = "_headers";
201
+ config = ["/*", ...hs.map(([k, v]) => ` ${k}: ${v}`)].join("\n");
202
+ break;
203
+ case "vercel":
204
+ filename = "vercel.json";
205
+ config = JSON.stringify({ headers: [{ source: "/(.*)", headers: hs.map(([key, value]) => ({ key, value })) }] }, null, 2);
206
+ break;
207
+ case "nginx":
208
+ filename = "your server { } block";
209
+ config = ["server_tokens off;", ...hs.map(([k, v]) => `add_header ${k} "${v}" always;`), 'proxy_hide_header X-Powered-By; # only if you proxy to another app'].join("\n");
210
+ break;
211
+ case "apache":
212
+ filename = ".htaccess or your VirtualHost";
213
+ config = ["ServerTokens Prod # server config only, not .htaccess", "<IfModule mod_headers.c>", ...hs.map(([k, v]) => ` Header always set ${k} "${v}"`), " Header always unset X-Powered-By", "</IfModule>"].join("\n");
214
+ break;
215
+ case "caddy":
216
+ filename = "Caddyfile (inside your site block)";
217
+ config = ["header {", ...hs.map(([k, v]) => ` ${k} "${v}"`), " -Server", " -X-Powered-By", "}"].join("\n");
218
+ break;
219
+ case "express":
220
+ filename = "your Express app";
221
+ config = ['app.disable("x-powered-by");', "app.use((req, res, next) => {", ...hs.map(([k, v]) => ` res.setHeader(${JSON.stringify(k)}, ${JSON.stringify(v)});`), " next();", "});"].join("\n");
222
+ break;
223
+ }
224
+ const notes = [
225
+ "Strict-Transport-Security only takes effect over HTTPS, and browsers remember it for a year. Make sure every subdomain supports HTTPS before using includeSubDomains.",
226
+ o.hstsPreload ? "HSTS preload is very hard to undo (removal takes months). Only keep it if you intend to submit the domain to the preload list." : "HSTS preload is left off on purpose, because it is very hard to undo. Add it later if you want browsers to ship your domain as HTTPS-only.",
227
+ "Cross-Origin-Opener-Policy: same-origin can break pop-up based sign-in (OAuth) and window.opener tricks. Test your login flow.",
228
+ "X-Frame-Options is the older clickjacking header. Modern browsers use CSP frame-ancestors, so keep both.",
229
+ ];
230
+ if (!o.csp)
231
+ notes.push("No Content-Security-Policy was included because a good one depends on your page. Use generate_csp, then pass its policy here.");
232
+ else if ((o.cspMode ?? "report-only") === "report-only")
233
+ notes.push("The CSP is report-only, so nothing is blocked yet. Switch cspMode to enforce once the console is clean.");
234
+ if (platform === "nginx")
235
+ notes.push("In nginx, add_header directives in a location block replace those from the server block. Repeat them there if you use location blocks with their own add_header.");
236
+ return { config, filename, notes };
237
+ }
238
+ export function formatSecurityHeaders(platform, r) {
239
+ const lang = platform === "vercel" ? "json" : platform === "express" ? "js" : platform === "apache" ? "apache" : platform === "nginx" ? "nginx" : "text";
240
+ const fence = "`".repeat(3);
241
+ return [`## Security headers for ${platform}`, `Put this in: ${r.filename}`, "", `${fence}${lang}`, r.config, fence, "", "### Notes", ...r.notes.map((n) => `- ${n}`)].join("\n");
242
+ }