nuxt-security
Version:
🛡️ Security Module for Nuxt based on HTTP Headers and Middleware
28 lines (27 loc) • 1.17 kB
JavaScript
import { defineNitroPlugin } from "#imports";
import { resolveSecurityRules } from "../context/index.js";
import { headerStringFromObject } from "../../../utils/headers";
export default defineNitroPlugin((nitroApp) => {
if (!import.meta.prerender) {
return;
}
nitroApp.hooks.hook("render:html", (html, { event }) => {
const rules = resolveSecurityRules(event);
if (!rules.enabled) {
return;
}
if (rules.ssg && rules.ssg.meta && rules.headers && rules.headers.contentSecurityPolicy) {
const csp = structuredClone(rules.headers.contentSecurityPolicy);
csp["frame-ancestors"] = false;
const headerValue = headerStringFromObject("contentSecurityPolicy", csp);
let insertIndex = 0;
if (html.head.length > 0) {
const metaCharsetMatch = html.head[0].match(/^<meta charset="(.*?)">/mdi);
if (metaCharsetMatch && metaCharsetMatch.indices) {
insertIndex = metaCharsetMatch.indices[0][1];
}
html.head[0] = html.head[0].slice(0, insertIndex) + `<meta http-equiv="Content-Security-Policy" content="${headerValue}">` + html.head[0].slice(insertIndex);
}
}
});
});