eslint-plugin-vue
Version:
Official ESLint plugin for Vue.js
77 lines (76 loc) • 2.99 kB
JavaScript
const require_index = require("../utils/index.js");
// lib/rules/no-template-target-blank.ts
/**
* @fileoverview disallow target="_blank" attribute without rel="noopener noreferrer"
* @author Sosukesuzuki
*/
function isTargetBlank(node) {
return node.key && node.key.name === "target" && node.value && node.value.value === "_blank";
}
function hasSecureRel(node, isReferrerAllowed) {
return node.attributes.some((attr) => {
if (attr.key && attr.key.name === "rel") {
const tags = attr.value && attr.value.type === "VLiteral" && attr.value.value.toLowerCase().split(" ");
return tags && tags.includes("noopener") && (isReferrerAllowed || tags.includes("noreferrer"));
}
return false;
});
}
function hasExternalLink(node) {
return node.attributes.some((attr) => attr.key && attr.key.name === "href" && attr.value && attr.value.type === "VLiteral" && /^(?:\w+:|\/\/)/.test(attr.value.value));
}
function hasDynamicLink(node) {
return node.attributes.some((attr) => attr.key && attr.key.type === "VDirectiveKey" && attr.key.name && attr.key.name.name === "bind" && attr.key.argument && attr.key.argument.type === "VIdentifier" && attr.key.argument.name === "href");
}
function getSuggestion(node) {
const relAttributeNode = node.parent.attributes.find((attribute) => attribute.key.name === "rel");
if (relAttributeNode) return {
desc: "Change `rel` attribute value to `noopener noreferrer`.",
fix(fixer) {
return fixer.replaceText(relAttributeNode, "rel=\"noopener noreferrer\"");
}
};
return {
desc: "Add `rel=\"noopener noreferrer\"`.",
fix(fixer) {
return fixer.insertTextAfter(node, " rel=\"noopener noreferrer\"");
}
};
}
var no_template_target_blank_default = {
meta: {
type: "problem",
docs: {
description: "disallow target=\"_blank\" attribute without rel=\"noopener noreferrer\"",
categories: void 0,
url: "https://eslint.vuejs.org/rules/no-template-target-blank.html"
},
hasSuggestions: true,
schema: [{
type: "object",
properties: {
allowReferrer: { type: "boolean" },
enforceDynamicLinks: { enum: ["always", "never"] }
},
additionalProperties: false
}],
messages: { missingRel: "Using target=\"_blank\" without rel=\"noopener noreferrer\" is a security risk." }
},
/**
* Creates AST event handlers for no-template-target-blank
*/
create(context) {
const configuration = context.options[0] || {};
const allowReferrer = configuration.allowReferrer || false;
const enforceDynamicLinks = configuration.enforceDynamicLinks || "always";
return require_index.default.defineTemplateBodyVisitor(context, { "VAttribute[directive=false]"(node) {
if (!isTargetBlank(node) || hasSecureRel(node.parent, allowReferrer)) return;
if (hasExternalLink(node.parent) || enforceDynamicLinks === "always" && hasDynamicLink(node.parent)) context.report({
node,
messageId: "missingRel",
suggest: [getSuggestion(node)]
});
} });
}
};
exports.default = no_template_target_blank_default;