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,271 @@
1
+ import { parseHtml, decodeEntities } from "./htmlscan.js";
2
+ import { scanSecrets } from "./secrets.js";
3
+ /* --------------------------------- CSP parsing -------------------------------- */
4
+ export function parseCsp(value) {
5
+ const out = {};
6
+ for (const part of value.split(";")) {
7
+ const tokens = part.trim().split(/\s+/).filter(Boolean);
8
+ if (!tokens.length)
9
+ continue;
10
+ const name = tokens[0].toLowerCase();
11
+ if (!(name in out))
12
+ out[name] = tokens.slice(1);
13
+ }
14
+ return out;
15
+ }
16
+ const TRACKERS = [
17
+ ["google-analytics.com", "Google Analytics"], ["googletagmanager.com", "Google Tag Manager"], ["doubleclick.net", "Google Ads"],
18
+ ["googlesyndication.com", "Google AdSense"], ["connect.facebook.net", "Meta Pixel"], ["facebook.com", "Meta"],
19
+ ["hotjar.com", "Hotjar"], ["clarity.ms", "Microsoft Clarity"], ["segment.com", "Segment"], ["segment.io", "Segment"],
20
+ ["mixpanel.com", "Mixpanel"], ["amplitude.com", "Amplitude"], ["fullstory.com", "FullStory"], ["intercom.io", "Intercom"],
21
+ ["hs-scripts.com", "HubSpot"], ["hsforms.net", "HubSpot"], ["analytics.tiktok.com", "TikTok Pixel"], ["snap.licdn.com", "LinkedIn Insight"],
22
+ ["ads-twitter.com", "X (Twitter) Ads"], ["ct.pinterest.com", "Pinterest Tag"], ["criteo.com", "Criteo"], ["taboola.com", "Taboola"],
23
+ ["outbrain.com", "Outbrain"], ["nr-data.net", "New Relic"], ["cloudflareinsights.com", "Cloudflare Web Analytics"],
24
+ ["plausible.io", "Plausible"], ["matomo.cloud", "Matomo"], ["heapanalytics.com", "Heap"], ["crazyegg.com", "Crazy Egg"],
25
+ ];
26
+ const hostMatches = (host, domain) => host === domain || host.endsWith("." + domain);
27
+ const URL_ATTRS = {
28
+ script: ["src"], img: ["src"], iframe: ["src"], link: ["href"], source: ["src"], video: ["src", "poster"], audio: ["src"],
29
+ embed: ["src"], object: ["data"], form: ["action"], a: ["href"],
30
+ };
31
+ /** Resolve an attribute URL against the page. Returns null for non-network values. */
32
+ function resolveUrl(raw, base) {
33
+ if (!raw)
34
+ return null;
35
+ const v = raw.trim();
36
+ if (!v || /^(data|blob|javascript|mailto|tel|about|#)/i.test(v))
37
+ return null;
38
+ try {
39
+ return new URL(v.startsWith("//") ? "https:" + v : v, base);
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ const CRED_COOKIE = /(sess|sid|token|auth|jwt|login|csrf|xsrf|remember)/i;
46
+ export function analyzeSecurity(i) {
47
+ const findings = [];
48
+ const good = [];
49
+ const add = (sev, area, msg, fix) => findings.push({ sev, area, msg, fix });
50
+ const h = i.headers;
51
+ const final = new URL(i.finalUrl);
52
+ const https = final.protocol === "https:";
53
+ const isHtml = (i.contentType ?? h["content-type"] ?? "").toLowerCase().includes("html");
54
+ /* ---- Transport ---- */
55
+ if (!https)
56
+ add("high", "transport", "The page is served over plain HTTP, so anything sent to or from it can be read or changed on the network.", "Serve the site over HTTPS and redirect all HTTP traffic to it.");
57
+ else
58
+ good.push("Served over HTTPS");
59
+ const start = new URL(i.url);
60
+ if (start.protocol === "http:" && https)
61
+ good.push("HTTP requests redirect to HTTPS");
62
+ if (start.protocol === "http:" && !https)
63
+ add("high", "transport", "http:// does not redirect to https://.", "Add a permanent redirect from HTTP to HTTPS.");
64
+ const downgrade = i.chain.find((c) => c.location && c.url.startsWith("https:") && c.location.startsWith("http:"));
65
+ if (downgrade)
66
+ add("high", "transport", `A redirect sends visitors from HTTPS back to HTTP (${new URL(downgrade.url).host}).`, "Never redirect from https:// to http://.");
67
+ if (https) {
68
+ const hsts = h["strict-transport-security"];
69
+ if (!hsts)
70
+ add("medium", "headers", "No Strict-Transport-Security (HSTS) header, so browsers can be tricked into using HTTP.", "Send Strict-Transport-Security: max-age=31536000; includeSubDomains");
71
+ else {
72
+ const age = Number(/max-age=(\d+)/i.exec(hsts)?.[1] ?? 0);
73
+ if (age < 15552000)
74
+ add("medium", "headers", `HSTS max-age is only ${age} seconds (${Math.round(age / 86400)} days).`, "Use at least 15552000 (180 days); 31536000 (one year) is the common choice.");
75
+ else
76
+ good.push("HSTS is enabled with a long max-age");
77
+ if (!/includesubdomains/i.test(hsts))
78
+ add("low", "headers", "HSTS does not cover subdomains.", "Add includeSubDomains once every subdomain supports HTTPS.");
79
+ }
80
+ }
81
+ /* ---- Content-Security-Policy ---- */
82
+ const cspHeader = h["content-security-policy"];
83
+ const cspRO = h["content-security-policy-report-only"];
84
+ const csp = cspHeader ? parseCsp(cspHeader) : null;
85
+ if (!csp) {
86
+ add("medium", "csp", cspRO ? "Only a Content-Security-Policy-Report-Only header is set, so nothing is blocked yet." : "No Content-Security-Policy header, so injected scripts run freely if an XSS bug exists.", "Start with the policy from generate_csp in report-only mode, then enforce it.");
87
+ }
88
+ else {
89
+ good.push("Content-Security-Policy is set");
90
+ const scriptSrc = csp["script-src"] ?? csp["default-src"] ?? [];
91
+ const hasNonceOrHash = scriptSrc.some((t) => /^'(nonce|sha256|sha384|sha512)-/.test(t));
92
+ if (scriptSrc.includes("'unsafe-inline'") && !hasNonceOrHash)
93
+ add("medium", "csp", "script-src allows 'unsafe-inline', which cancels most of the protection against XSS.", "Replace inline scripts with files, or allow them with nonces or hashes (generate_csp computes hashes).");
94
+ if (scriptSrc.includes("'unsafe-eval'"))
95
+ add("medium", "csp", "script-src allows 'unsafe-eval'.", "Remove eval-like code, then drop 'unsafe-eval'.");
96
+ if (scriptSrc.includes("*") || scriptSrc.some((t) => t === "https:" || t === "http:" || t === "data:"))
97
+ add("medium", "csp", "script-src allows scripts from almost anywhere (a bare *, https:, http: or data:).", "List only the hosts you really load scripts from.");
98
+ if (!("object-src" in csp) && !("default-src" in csp))
99
+ add("low", "csp", "No object-src, so plugins are not blocked.", "Add object-src 'none'.");
100
+ else if ((csp["object-src"] ?? csp["default-src"] ?? []).some((t) => t !== "'none'") && "object-src" in csp)
101
+ add("low", "csp", "object-src is not 'none'.", "Add object-src 'none'.");
102
+ if (!("base-uri" in csp))
103
+ add("low", "csp", "No base-uri, so an injected <base> tag can redirect relative URLs.", "Add base-uri 'self'.");
104
+ if (!("frame-ancestors" in csp) && !h["x-frame-options"])
105
+ add("medium", "csp", "No frame-ancestors in the CSP and no X-Frame-Options, so other sites can frame this page (clickjacking).", "Add frame-ancestors 'self' (or 'none').");
106
+ }
107
+ /* ---- Other headers ---- */
108
+ const xfo = h["x-frame-options"]?.toLowerCase();
109
+ if (csp?.["frame-ancestors"] || xfo === "deny" || xfo === "sameorigin")
110
+ good.push("Clickjacking protection (frame-ancestors or X-Frame-Options)");
111
+ else if (xfo)
112
+ add("low", "headers", `X-Frame-Options has an unsupported value ("${h["x-frame-options"]}").`, "Use DENY or SAMEORIGIN, or better, CSP frame-ancestors.");
113
+ if ((h["x-content-type-options"] ?? "").toLowerCase() === "nosniff")
114
+ good.push("X-Content-Type-Options: nosniff");
115
+ else
116
+ add("medium", "headers", "Missing X-Content-Type-Options: nosniff, so browsers may guess file types and run uploaded content as script.", "Send X-Content-Type-Options: nosniff");
117
+ const ref = (h["referrer-policy"] ?? "").toLowerCase();
118
+ if (!ref)
119
+ add("low", "headers", "No Referrer-Policy, so full URLs (which may contain private data) can leak to other sites.", "Send Referrer-Policy: strict-origin-when-cross-origin");
120
+ else if (/unsafe-url|no-referrer-when-downgrade/.test(ref))
121
+ add("low", "headers", `Referrer-Policy "${ref}" leaks full URLs to other sites.`, "Use strict-origin-when-cross-origin or stricter.");
122
+ else
123
+ good.push("Referrer-Policy is set");
124
+ if (!h["permissions-policy"])
125
+ add("low", "headers", "No Permissions-Policy, so powerful features (camera, microphone, location) are not explicitly limited.", "Send a Permissions-Policy that disables the features you do not use.");
126
+ else
127
+ good.push("Permissions-Policy is set");
128
+ if (!h["cross-origin-opener-policy"])
129
+ add("info", "headers", "No Cross-Origin-Opener-Policy.", "Consider Cross-Origin-Opener-Policy: same-origin (check that popups and OAuth flows still work).");
130
+ /* ---- Information disclosure ---- */
131
+ const server = h["server"];
132
+ if (server && /\d+\.\d+/.test(server))
133
+ add("low", "disclosure", `The Server header reveals a version ("${server}").`, "Hide version numbers (nginx: server_tokens off; Apache: ServerTokens Prod).");
134
+ if (h["x-powered-by"])
135
+ add("low", "disclosure", `X-Powered-By reveals the technology ("${h["x-powered-by"]}").`, "Remove the X-Powered-By header.");
136
+ if (h["x-aspnet-version"] || h["x-aspnetmvc-version"])
137
+ add("low", "disclosure", "An ASP.NET version header is sent.", "Remove X-AspNet-Version and X-AspNetMvc-Version.");
138
+ const acao = h["access-control-allow-origin"];
139
+ if (acao === "*" && /true/i.test(h["access-control-allow-credentials"] ?? ""))
140
+ add("high", "headers", "CORS allows every origin with credentials.", "Never combine Access-Control-Allow-Origin: * with credentials; allow specific origins.");
141
+ else if (acao === "*")
142
+ add("info", "headers", "CORS allows any origin to read responses (Access-Control-Allow-Origin: *). Fine for public data, wrong for anything private.");
143
+ /* ---- Cookies (names only, values are never read out) ---- */
144
+ for (const raw of i.setCookies) {
145
+ const name = raw.split("=")[0].trim();
146
+ const attrs = raw.split(";").slice(1).map((a) => a.trim().toLowerCase());
147
+ const has = (a) => attrs.some((x) => x === a || x.startsWith(a + "="));
148
+ const sameSite = attrs.find((a) => a.startsWith("samesite="))?.split("=")[1];
149
+ const sensitive = CRED_COOKIE.test(name);
150
+ if (https && !has("secure"))
151
+ add(sensitive ? "high" : "medium", "cookies", `Cookie "${name}" is missing Secure, so it can be sent over HTTP.`, "Add the Secure attribute.");
152
+ if (!has("httponly") && sensitive)
153
+ add("high", "cookies", `Cookie "${name}" looks like a session or token and is missing HttpOnly, so scripts (and XSS) can read it.`, "Add HttpOnly.");
154
+ if (!sameSite)
155
+ add("low", "cookies", `Cookie "${name}" has no SameSite attribute.`, "Add SameSite=Lax (or Strict).");
156
+ else if (sameSite === "none" && !has("secure"))
157
+ add("medium", "cookies", `Cookie "${name}" uses SameSite=None without Secure, which browsers reject.`, "Add Secure when using SameSite=None.");
158
+ }
159
+ if (i.setCookies.length && !findings.some((f) => f.area === "cookies"))
160
+ good.push(`${i.setCookies.length} cookie${i.setCookies.length > 1 ? "s" : ""} set with safe attributes`);
161
+ /* ---- HTML content ---- */
162
+ const thirdParties = new Set();
163
+ const trackers = [];
164
+ if (isHtml && i.body) {
165
+ const p = parseHtml(i.body);
166
+ const pageHost = final.hostname.replace(/^www\./, "");
167
+ const isThird = (host) => !(host === pageHost || host.endsWith("." + pageHost) || hostMatches(final.hostname, host));
168
+ const mixedActive = [];
169
+ const mixedPassive = [];
170
+ const noSri = [];
171
+ let jsUrls = 0, blankNoRel = 0;
172
+ const consider = (t) => {
173
+ for (const attr of URL_ATTRS[t.name] ?? []) {
174
+ const u = resolveUrl(t.attrs[attr], i.finalUrl);
175
+ if (!u)
176
+ continue;
177
+ if (isThird(u.hostname) && t.name !== "a" && t.name !== "form")
178
+ thirdParties.add(u.hostname);
179
+ if (https && u.protocol === "http:") {
180
+ const active = t.name === "script" || t.name === "iframe" || t.name === "object" || t.name === "embed" || (t.name === "link" && /stylesheet/i.test(t.attrs.rel ?? ""));
181
+ if (t.name === "a")
182
+ continue; // plain links are not mixed content
183
+ (active ? mixedActive : mixedPassive).push(u.href);
184
+ }
185
+ const sriNeeded = (t.name === "script" && attr === "src") || (t.name === "link" && /stylesheet/i.test(t.attrs.rel ?? ""));
186
+ if (sriNeeded && isThird(u.hostname) && !t.attrs.integrity)
187
+ noSri.push(`${t.name === "script" ? "script" : "stylesheet"} ${u.hostname}`);
188
+ }
189
+ };
190
+ for (const t of p.tags)
191
+ consider(t);
192
+ if (mixedActive.length)
193
+ add("high", "content", `${mixedActive.length} script/frame/stylesheet load${mixedActive.length > 1 ? "" : "s"} over http:// on an https:// page (blocked or exploitable): ${mixedActive.slice(0, 3).join(", ")}.`, "Load every resource over https://.");
194
+ if (mixedPassive.length)
195
+ add("medium", "content", `${mixedPassive.length} image/media resource${mixedPassive.length > 1 ? "s load" : " loads"} over http:// on an https:// page.`, "Use https:// URLs for all resources.");
196
+ const noSriScripts = noSri.filter((x) => x.startsWith("script"));
197
+ const noSriStyles = noSri.filter((x) => x.startsWith("stylesheet"));
198
+ if (noSriScripts.length)
199
+ add("medium", "content", `${noSriScripts.length} third-party script${noSriScripts.length > 1 ? "s" : ""} without Subresource Integrity (${[...new Set(noSriScripts.map((s) => s.slice(7)))].slice(0, 4).join(", ")}). If that host is compromised, so is your page.`, "Add integrity=\"sha384-...\" and crossorigin=\"anonymous\" for static third-party files, or self-host them.");
200
+ if (noSriStyles.length)
201
+ add("low", "content", `${noSriStyles.length} third-party stylesheet${noSriStyles.length > 1 ? "s" : ""} without Subresource Integrity.`, "Add an integrity attribute, or self-host the stylesheet.");
202
+ for (const f of p.tags.filter((t) => t.name === "form")) {
203
+ const action = resolveUrl(f.attrs.action, i.finalUrl);
204
+ if (action?.protocol === "http:")
205
+ add("high", "content", `A form posts to an http:// address (${action.hostname}), sending what users type in the clear.`, "Point the form action at an https:// URL.");
206
+ }
207
+ const pw = p.tags.filter((t) => t.name === "input" && (t.attrs.type ?? "").toLowerCase() === "password");
208
+ if (pw.length && !https)
209
+ add("high", "content", "A password field is on a page that is not served over HTTPS.", "Serve every page with a login form over HTTPS.");
210
+ if (pw.some((t) => !t.attrs.autocomplete))
211
+ add("low", "content", "A password field has no autocomplete attribute, which hurts password managers.", 'Use autocomplete="current-password" or "new-password".');
212
+ for (const t of p.tags) {
213
+ for (const attr of ["href", "src", "action"])
214
+ if (/^\s*javascript:/i.test(t.attrs[attr] ?? ""))
215
+ jsUrls++;
216
+ if (t.name === "a" && (t.attrs.target ?? "").toLowerCase() === "_blank" && !/noopener|noreferrer/i.test(t.attrs.rel ?? ""))
217
+ blankNoRel++;
218
+ }
219
+ if (jsUrls)
220
+ add("medium", "content", `${jsUrls} javascript: URL${jsUrls > 1 ? "s" : ""} in attributes, which a strict CSP would block.`, "Use real links and event listeners instead.");
221
+ if (blankNoRel)
222
+ add("low", "content", `${blankNoRel} link${blankNoRel > 1 ? "s open" : " opens"} a new tab (target="_blank") without rel="noopener". Current browsers imply it, older ones do not.`, 'Add rel="noopener noreferrer".');
223
+ const handlers = p.tags.reduce((n, t) => n + Object.keys(t.attrs).filter((a) => /^on[a-z]+$/.test(a)).length, 0);
224
+ const inlineScripts = p.scripts.filter((s) => !s.attrs.src && !/json|importmap|speculation/i.test(s.attrs.type ?? "")).length;
225
+ if (handlers || inlineScripts)
226
+ add("info", "csp", `${inlineScripts} inline script${inlineScripts === 1 ? "" : "s"} and ${handlers} inline event handler${handlers === 1 ? "" : "s"}. A strict CSP needs inline scripts hashed or moved to files, and handlers replaced with event listeners.`);
227
+ const generator = p.tags.find((t) => t.name === "meta" && t.attrs.name?.toLowerCase() === "generator");
228
+ if (generator?.attrs.content && /\d+\.\d+/.test(generator.attrs.content))
229
+ add("low", "disclosure", `The page names its software and version ("${generator.attrs.content}").`, "Remove the generator meta tag or hide the version.");
230
+ if (p.tags.some((t) => t.name === "meta" && t.attrs["http-equiv"]?.toLowerCase() === "content-security-policy") && !cspHeader)
231
+ add("info", "csp", "A CSP is set only through a <meta> tag. Meta policies cannot use frame-ancestors or report-uri.", "Send the policy as an HTTP header.");
232
+ const secrets = scanSecrets(i.body);
233
+ if (secrets.length)
234
+ add("high", "content", `${secrets.length} possible credential${secrets.length > 1 ? "s" : ""} in the page source (${[...new Set(secrets.map((s) => s.rule))].slice(0, 3).join(", ")}). Anyone can read them.`, "Run scan_secrets on the source for exact locations, revoke the credentials and move them server-side.");
235
+ // Privacy
236
+ for (const host of thirdParties) {
237
+ const t = TRACKERS.find(([d]) => hostMatches(host, d));
238
+ if (t)
239
+ trackers.push({ host, name: t[1] });
240
+ }
241
+ if (trackers.length)
242
+ add("info", "privacy", `Known tracking or analytics services load on this page: ${[...new Set(trackers.map((t) => t.name))].join(", ")}. They may need consent under GDPR and similar laws.`, "Disclose them in your privacy policy and load them only after consent where required.");
243
+ if ([...thirdParties].some((x) => hostMatches(x, "fonts.googleapis.com") || hostMatches(x, "fonts.gstatic.com")))
244
+ add("info", "privacy", "Fonts load from Google's servers, which shares visitors' IP addresses with Google (a GDPR concern in some courts).", "Self-host the font files.");
245
+ }
246
+ /* ---- Score ---- */
247
+ const weights = { high: 15, medium: 7, low: 2, info: 0 };
248
+ const score = Math.max(0, 100 - findings.reduce((n, f) => n + weights[f.sev], 0));
249
+ const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 55 ? "D" : "F";
250
+ return { score, grade, findings, good, thirdParties: [...thirdParties].sort(), trackers };
251
+ }
252
+ export function formatSecurityReport(r, i) {
253
+ const count = (s) => r.findings.filter((f) => f.sev === s).length;
254
+ const lines = [
255
+ `## Security check: ${new URL(i.finalUrl).host}`,
256
+ `Grade **${r.grade}** · score ${r.score}/100 · ${count("high")} high, ${count("medium")} medium, ${count("low")} low, ${count("info")} notes`,
257
+ `Checked one ${i.status} response from ${i.finalUrl}${i.chain.length ? ` after ${i.chain.length} redirect${i.chain.length > 1 ? "s" : ""}` : ""}. Only what the server sends to any visitor was inspected.`,
258
+ ];
259
+ for (const [sev, title] of [["high", "High"], ["medium", "Medium"], ["low", "Low"], ["info", "Notes"]]) {
260
+ const list = r.findings.filter((f) => f.sev === sev);
261
+ if (list.length)
262
+ lines.push("", `### ${title}`, ...list.map((f) => `- [${f.area}] ${f.msg}${f.fix ? ` **Fix:** ${f.fix}` : ""}`));
263
+ }
264
+ if (r.good.length)
265
+ lines.push("", "### Already good", ...r.good.map((g) => `- ${g}`));
266
+ if (r.thirdParties.length)
267
+ lines.push("", `### Third-party hosts (${r.thirdParties.length})`, r.thirdParties.slice(0, 20).join(", ") + (r.thirdParties.length > 20 ? ", ..." : ""));
268
+ lines.push("", "_Next: `generate_csp` builds a Content-Security-Policy from this page, and `generate_security_headers` writes the header set for your host. This is a passive check of headers and markup; it does not test for vulnerabilities in your code._");
269
+ return lines.join("\n");
270
+ }
271
+ export { decodeEntities };