Follow the user's requirements carefully & to the letter.
First think step-by-step -- describe your plan for what to build in psuedocode, written out in great detail
Then output the code in a single codeblock
Minimize any other prose
I am writing a conformance test (similar to ESLint) in TypeScript for detecting when a user does not use rel="noopener" when using window.open. The issue this causes is breaking the bfcache integrity in the browser. Some more details here:
code
# Avoid window.opener references
In some browsers (including Chromium-based browsers) if a page was opened using window.open() or (in Chromium-based browsers prior to version 88) from a link with target=_blank—without specifying rel="noopener"—then the opening page will have a reference to the window object of the opened page.
In addition to being a security risk, a page with a non-null window.opener reference cannot safely be put into the bfcache because that could break any pages attempting to access it.
As a result, it's best to avoid creating window.opener references by using rel="noopener" whenever possible. If your site requires opening a window and controlling it through window.postMessage() or directly referencing the window object, neither the opened window nor the opener will be eligible for bfcache.
Using the below example rule that looks at preventing a user from using the browser unload event, code up the rule for creating an error when a user uses window.open without rel="noopener":
import { stripIndents } from 'common-tags';
import type { AST } from '@typescript-eslint/typescript-estree';
import {
AST_NODE_TYPES,
simpleTraverse,
} from '@typescript-eslint/typescript-estree';
import type { ConformanceError } from '../conformance-error';
import type { ProjectData } from '../project-data';
import { convertPositionToRange } from '../utils/convert-position-to-range';
const ERROR_MESSAGE = stripIndents The \unload` event does not fire reliably and listening for it can prevent browser optimizations like the Back-Forward Cache (bfcache).
Consider using the `pagehide`, `visibilitychange`, or `beforeunload` events instead.
const { left } = node;
if (left.type !== AST_NODE_TYPES.MemberExpression) return;
const { object, property } = left;
if (object.type !== AST_NODE_TYPES.Identifier) return;
if (object.name !== 'window') return;
if (property.type !== AST_NODE_TYPES.Identifier) return;
if (property.name !== 'onunload') return;
errors.push({
testName: TEST_NAME,
location: {
workspace: workspaceName,
filePath,
range: convertPositionToRange(node.loc),
},
message: ERROR_MESSAGE,
});
},
// Detect `window.addEventListener('unload')` calls.
CallExpression(node, _parent) {
if (node.type !== AST_NODE_TYPES.CallExpression) return;
const { callee } = node;
if (callee.type !== AST_NODE_TYPES.MemberExpression) return;
const { object, property } = callee;
if (object.type !== AST_NODE_TYPES.Identifier) return;
if (object.name !== 'window') return;
if (property.type !== AST_NODE_TYPES.Identifier) return;
if (property.name !== 'addEventListener') return;
const [eventTypeNode] = node.arguments;
if (eventTypeNode?.type !== AST_NODE_TYPES.Literal) return;
if (eventTypeNode.value !== 'unload') return;
errors.push({
testName: TEST_NAME,
location: {
workspace: workspaceName,
filePath,
range: convertPositionToRange(node.loc),
},
message: ERROR_MESSAGE,
});
},
});
return errors;
}
Pseudocode Plan for window.open without rel="noopener" Conformance Test
Rule Name: BFCACHE_INTEGRITY_WINDOW_OPEN_NOOPENER
Objective: Detect and report errors when window.open is used without rel="noopener"
Step-by-Step Pseudocode:
Configuration Check
Retrieve conformance configuration for the project
If BFCACHE_INTEGRITY_WINDOW_OPEN_NOOPENER test is not enabled, RETURN EMPTY ERRORS ARRAY
AST Traversal Setup
Initialize errors array
Define traversal callbacks for the Abstract Syntax Tree (AST)
Detect window.open Calls
Callback for CallExpression nodes
Check if node is a CallExpression
Verify callee is a MemberExpression with:
object being an Identifier named 'window'
property being an Identifier named 'open'
If verified, PROCEED TO ARGUMENT ANALYSIS
Analyze window.open Arguments
Check for absence of rel="noopener" in options
Iterate through node.arguments (expected to be at least one, the URL)
If a second argument (options object) exists:
Check if it's an ObjectExpression
Iterate through its properties
If a property named 'rel' with value not including 'noopener' is found, MARK AS ERROR
If no options object or no 'rel' property, MARK AS ERROR (assuming no 'noopener')
Error Reporting
For each marked error:
Create a ConformanceError object with:
testName: BFCACHE_INTEGRITY_WINDOW_OPEN_NOOPENER
location: derived from node.loc, including workspaceName, filePath, and range
message: predefined error message (see below), including security implications
RETURN ERRORS ARRAY
Predefined Error Message:
markdown
Using `window.open` without `rel="noopener"` can break browser Back-Forward Cache (bfcache) integrity, posing security risks as it allows the new page to access and manipulate the original window, potentially leading to tabnabbing attacks. This also prevents the opened page and the opener from being cached, affecting performance.
Ensure to include `rel="noopener"` in the options object passed to `window.open`.
See https://web.dev/bfcache for more information.
Code Implementation
typescript
Dataset releases
Not yet included in a published release.
import { stripIndents } from 'common-tags';
import type { AST } from '@typescript-eslint/typescript-estree';
import {
AST_NODE_TYPES,
simpleTraverse,
} from '@typescript-eslint/typescript-estree';
import type { ConformanceError } from '../conformance-error';
import type { ProjectData } from '../project-data';
import { convertPositionToRange } from '../utils/convert-position-to-range';
const TEST_NAME = 'BFCACHE_INTEGRITY_WINDOW_OPEN_NOOPENER';
const ERROR_MESSAGE = stripIndents`
Using \`window.open\` without \`rel="noopener"\` can break browser Back-Forward Cache (bfcache) integrity and pose security risks, as it allows the new page to access and manipulate the original window, potentially leading to tabnabbing attacks. This also prevents the opened page and the opener from being cached, affecting performance.
Ensure to include \`rel="noopener"\` in the options object passed to \`window.open\`.
See https://web.dev/bfcache for more information.
`;
/**
* Detects and reports usage of window.open without rel="noopener" to prevent bfcache integrity issues and security risks.
*
* @param projectData Project configuration and data
* @param filePath Path of the file being analyzed
* @param ast Abstract Syntax Tree of the file
* @returns Array of ConformanceError objects for each violation found
*/
export function windowOpenNoopener(
projectData: ProjectData,
filePath: string,
ast: AST<{
filePath: string;
loc: true;
range: false;
}>,
): ConformanceError[] {
// Check if the test is enabled in the project configuration
const conformanceConfig = projectData.getConformanceConfig();
if (!conformanceConfig.isTestEnabled(TEST_NAME)) return [];
const workspaceName = projectData.getWorkspaceName();
const errors: ConformanceError[] = [];
// Traverse the Abstract Syntax Tree to detect window.open calls
simpleTraverse(ast, {
CallExpression(node, _parent) {
// Ensure the node represents a function call
if (node.type !== AST_NODE_TYPES.CallExpression) return;
const { callee } = node;
// Verify the callee is window.open
if (callee.type !== AST_NODE_TYPES.MemberExpression) return;
const { object, property } = callee;
if (object.type !== AST_NODE_TYPES.Identifier || object.name !== 'window') return;
if (property.type !== AST_NODE_TYPES.Identifier || property.name !== 'open') return;
const [urlArg, optionsArg] = node.arguments;
// If no options object is provided, or if it's not an ObjectExpression, mark as error
if (!optionsArg || optionsArg.type !== AST_NODE_TYPES.ObjectExpression) {
errors.push(createError(node));
} else {
// Check if 'rel' property includes 'noopener'
const hasNoopenerRel = optionsArg.properties.some((prop) => {
return (
prop.type === AST_NODE_TYPES.Property &&
prop.key.type === AST_NODE_TYPES.Identifier &&
prop.key.name === 'rel' &&
prop.value.type === AST_NODE_TYPES.Literal &&
(typeof prop.value.value === 'string' && prop.value.value.includes('noopener'))
);
});
// If 'noopener' is not found, mark as error
if (!hasNoopenerRel) {
errors.push(createError(node));
}
}
},
});
return errors;
/**
* Creates a ConformanceError object for a window.open call without rel="noopener".
* @param node AST node representing the window.open call
* @returns ConformanceError object with details about the error location and message
*/
function createError(node: any) {
return {
testName: TEST_NAME,
location: {
workspace: workspaceName,
filePath,
range: convertPositionToRange(node.loc),
},
message: ERROR_MESSAGE,
};
}
}