eslint-plugin-browser-security 3.0.2 → 3.1.1
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.
package/AGENTS.md
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
<!-- Generated by scripts/generate-plugin-agents-md.ts from package.json and the plugin exports. Do not edit by hand; run `npm run agents-md`. -->
|
|
2
|
+
|
|
3
|
+
# eslint-plugin-browser-security
|
|
4
|
+
|
|
5
|
+
Guide for AI coding assistants using this plugin in a project. To change the plugin's own source, read https://github.com/ofri-peretz/eslint/blob/main/AGENTS.md instead.
|
|
6
|
+
|
|
7
|
+
> ESLint browser security and XSS rules — detects DOM XSS, postMessage abuse, tokens in localStorage, insecure cookies, clickjacking, mixed content, and CSP gaps.
|
|
8
|
+
|
|
9
|
+
## Enable it
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install --save-dev eslint-plugin-browser-security
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Requires ESLint ^8.40.0 || ^9.0.0 || ^10.0.0 and Node >=22.13.0.
|
|
16
|
+
|
|
17
|
+
Flat config files (`eslint.config.*`) are found by ESLint 8.57 and newer; on ESLint 9 and 10 they are the default.
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
// eslint.config.mjs
|
|
21
|
+
import browserSecurity from 'eslint-plugin-browser-security';
|
|
22
|
+
|
|
23
|
+
export default [browserSecurity.configs.recommended];
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Each preset is one flat config object: put it in the array as an element, do not spread it. Rule ids are prefixed `browser-security/`. Add it to the config you already have; do not remove other plugins. TypeScript files need a TypeScript parser in the config (`typescript-eslint`).
|
|
27
|
+
|
|
28
|
+
Use it alongside `eslint-plugin-security`, not instead of it: keep that plugin if the project has it. Measured overlap and the limits of both: https://eslint.interlace.tools/docs/getting-started/with-eslint-plugin-security
|
|
29
|
+
|
|
30
|
+
## Presets
|
|
31
|
+
|
|
32
|
+
| Preset | Rules | Errors | Warnings |
|
|
33
|
+
| ------------- | ----- | ------ | -------- |
|
|
34
|
+
| `flagship` | 1 | 1 | 0 |
|
|
35
|
+
| `recommended` | 33 | 32 | 1 |
|
|
36
|
+
| `strict` | 46 | 46 | 0 |
|
|
37
|
+
| `xss` | 2 | 2 | 0 |
|
|
38
|
+
| `storage` | 1 | 1 | 0 |
|
|
39
|
+
| `postmessage` | 2 | 2 | 0 |
|
|
40
|
+
| `websocket` | 1 | 1 | 0 |
|
|
41
|
+
| `cookies` | 1 | 1 | 0 |
|
|
42
|
+
|
|
43
|
+
### `flagship`
|
|
44
|
+
|
|
45
|
+
1 rule:
|
|
46
|
+
|
|
47
|
+
- `no-postmessage-wildcard-origin` (error): Disallow using wildcard (*) as targetOrigin in postMessage calls.
|
|
48
|
+
|
|
49
|
+
### `recommended`
|
|
50
|
+
|
|
51
|
+
33 rules:
|
|
52
|
+
|
|
53
|
+
- `no-innerhtml` (error): Disallow dangerous innerHTML/outerHTML assignments that can lead to XSS.
|
|
54
|
+
- `no-eval` (error): Disallow eval(), Function(), and other code execution patterns.
|
|
55
|
+
- `require-postmessage-origin-check` (error): Require origin validation in postMessage event listeners.
|
|
56
|
+
- `no-postmessage-wildcard-origin` (error): Disallow using wildcard (*) as targetOrigin in postMessage calls.
|
|
57
|
+
- `no-postmessage-innerhtml` (error): Disallow using innerHTML or similar methods with postMessage data.
|
|
58
|
+
- `no-sensitive-localstorage` (error): Disallow storing sensitive data like passwords and keys in localStorage.
|
|
59
|
+
- `no-jwt-in-storage` (error): Disallow storing JWTs and other bearer credentials in localStorage or sessionStorage.
|
|
60
|
+
- `no-sensitive-sessionstorage` (error): Disallow storing sensitive data in sessionStorage.
|
|
61
|
+
- `no-sensitive-indexeddb` (error): Disallow storing sensitive data in IndexedDB.
|
|
62
|
+
- `no-sensitive-cookie-js` (error): Disallow storing sensitive data (passwords, keys, regulated identifiers) in cookies via JavaScript.
|
|
63
|
+
- `no-cookie-auth-tokens` (error): Disallow storing auth tokens in cookies via JavaScript.
|
|
64
|
+
- `require-cookie-secure-attrs` (error): Require Secure and SameSite attributes when setting cookies.
|
|
65
|
+
- `require-websocket-wss` (error): Require secure WebSocket connections (wss://) instead of unencrypted (ws://).
|
|
66
|
+
- `no-websocket-innerhtml` (error): Disallow using innerHTML or similar methods with WebSocket message data.
|
|
67
|
+
- `no-websocket-eval` (error): Disallow using eval() or Function() with WebSocket message data.
|
|
68
|
+
- `no-filereader-innerhtml` (error): Disallow using innerHTML or similar methods with FileReader data.
|
|
69
|
+
- `require-blob-url-revocation` (warn): Require revoking Blob URLs to prevent memory leaks.
|
|
70
|
+
- `no-dynamic-service-worker-url` (error): Disallow dynamic URLs in service worker registration.
|
|
71
|
+
- `no-worker-message-innerhtml` (error): Disallow using innerHTML with Web Worker message data.
|
|
72
|
+
- `no-unsafe-inline-csp` (error): Disallow 'unsafe-inline' in Content Security Policy.
|
|
73
|
+
- `no-unsafe-eval-csp` (error): Disallow 'unsafe-eval' in Content Security Policy.
|
|
74
|
+
- `detect-mixed-content` (error): Detect HTTP resources in HTTPS pages.
|
|
75
|
+
- `no-unencrypted-transmission` (error): Detects unencrypted data transmission (HTTP vs HTTPS, plain text protocols).
|
|
76
|
+
- `no-allow-arbitrary-loads` (error): Prevent configuration allowing insecure loads.
|
|
77
|
+
- `no-credentials-in-query-params` (error): Disallow credentials in URL query parameters.
|
|
78
|
+
- `no-http-urls` (error): Disallow hardcoded HTTP URLs (require HTTPS).
|
|
79
|
+
- `no-incomplete-url-sanitization` (error): Disallow URL substring tests and partial scheme denylists as security decisions.
|
|
80
|
+
- `no-insecure-redirects` (error): Detects open redirect vulnerabilities.
|
|
81
|
+
- `no-disabled-certificate-validation` (error): Prevent disabled SSL/TLS certificate validation.
|
|
82
|
+
- `require-https-only` (error): Enforce HTTPS for all external requests.
|
|
83
|
+
- `no-insecure-websocket` (error): Require secure WebSocket connections (wss://).
|
|
84
|
+
- `no-unvalidated-deeplinks` (error): Require validation of deep link URLs.
|
|
85
|
+
- `no-client-side-auth-logic` (error): Prevent authentication logic in client code.
|
|
86
|
+
|
|
87
|
+
### `strict`
|
|
88
|
+
|
|
89
|
+
Everything in `recommended` plus 13 more (some shared rules run at a different severity here):
|
|
90
|
+
|
|
91
|
+
- `no-clickjacking` (error): Detects clickjacking vulnerabilities and missing frame protections.
|
|
92
|
+
- `no-missing-cors-check` (error): Detects missing CORS validation (wildcard CORS, missing origin check).
|
|
93
|
+
- `no-missing-csrf-protection` (error): Detects missing CSRF token validation in POST/PUT/DELETE requests.
|
|
94
|
+
- `no-missing-security-headers` (error): Detects missing security headers in HTTP responses.
|
|
95
|
+
- `no-password-in-url` (error): Prevent passwords in URLs.
|
|
96
|
+
- `no-permissive-cors` (error): Prevent overly permissive CORS configuration.
|
|
97
|
+
- `no-sensitive-data-in-analytics` (error): Prevent PII being sent to analytics services.
|
|
98
|
+
- `no-sensitive-data-in-cache` (error): Prevent caching credential-bearing responses in the Cache Storage API.
|
|
99
|
+
- `no-tracking-without-consent` (error): Require consent before analytics tracking.
|
|
100
|
+
- `no-unescaped-url-parameter` (error): Detects unescaped URL parameters.
|
|
101
|
+
- `require-csp-headers` (error): Require Content Security Policy headers.
|
|
102
|
+
- `require-url-validation` (error): Enforce URL validation before navigation.
|
|
103
|
+
- `require-mime-type-validation` (error): Require MIME type validation for file uploads.
|
|
104
|
+
|
|
105
|
+
### `xss`
|
|
106
|
+
|
|
107
|
+
2 rules:
|
|
108
|
+
|
|
109
|
+
- `no-innerhtml` (error): Disallow dangerous innerHTML/outerHTML assignments that can lead to XSS.
|
|
110
|
+
- `no-eval` (error): Disallow eval(), Function(), and other code execution patterns.
|
|
111
|
+
|
|
112
|
+
### `storage`
|
|
113
|
+
|
|
114
|
+
1 rule:
|
|
115
|
+
|
|
116
|
+
- `no-sensitive-localstorage` (error): Disallow storing sensitive data like passwords and keys in localStorage.
|
|
117
|
+
|
|
118
|
+
### `postmessage`
|
|
119
|
+
|
|
120
|
+
2 rules:
|
|
121
|
+
|
|
122
|
+
- `require-postmessage-origin-check` (error): Require origin validation in postMessage event listeners.
|
|
123
|
+
- `no-postmessage-wildcard-origin` (error): Disallow using wildcard (*) as targetOrigin in postMessage calls.
|
|
124
|
+
|
|
125
|
+
### `websocket`
|
|
126
|
+
|
|
127
|
+
1 rule:
|
|
128
|
+
|
|
129
|
+
- `require-websocket-wss` (error): Require secure WebSocket connections (wss://) instead of unencrypted (ws://).
|
|
130
|
+
|
|
131
|
+
### `cookies`
|
|
132
|
+
|
|
133
|
+
1 rule:
|
|
134
|
+
|
|
135
|
+
- `no-sensitive-cookie-js` (error): Disallow storing sensitive data (passwords, keys, regulated identifiers) in cookies via JavaScript.
|
|
136
|
+
|
|
137
|
+
## Other Interlace plugins by dependency
|
|
138
|
+
|
|
139
|
+
If the project also depends on one of these, add the matching plugin the same way:
|
|
140
|
+
|
|
141
|
+
- `express`, `fastify`, `koa`, `@hapi/hapi`, `restify`, `hono`, `next`, `@nestjs/core`, `@nestjs/common`, `aws-lambda`, `@types/aws-lambda`, `@middy/core`, `commander`, `yargs`, `@oclif/core`, `@modelcontextprotocol/*`: `eslint-plugin-node-security`
|
|
142
|
+
- `express`: `eslint-plugin-express-security`
|
|
143
|
+
- `@nestjs/common`, `@nestjs/core`: `eslint-plugin-nestjs-security`
|
|
144
|
+
- `jsonwebtoken`, `jose`, `express-jwt`, `@nestjs/jwt`, `jwks-rsa`, `jwt-decode`: `eslint-plugin-jwt-security`
|
|
145
|
+
- `pg`, `pg-pool`, `pg-promise`, `postgres`, `slonik`: `eslint-plugin-postgresql-security`
|
|
146
|
+
- `mysql2`, `mysql`: `eslint-plugin-mysql-security`
|
|
147
|
+
- `mongodb`, `mongoose`: `eslint-plugin-mongodb-security`
|
|
148
|
+
- `better-sqlite3`, `sqlite3`: `eslint-plugin-sqlite-security`
|
|
149
|
+
- `knex`: `eslint-plugin-knex-security`
|
|
150
|
+
- `@prisma/client`, `prisma`: `eslint-plugin-prisma-security`
|
|
151
|
+
- `drizzle-orm`: `eslint-plugin-drizzle-security`
|
|
152
|
+
- `sequelize`: `eslint-plugin-sequelize-security`
|
|
153
|
+
- `typeorm`: `eslint-plugin-typeorm-security`
|
|
154
|
+
- `@supabase/supabase-js`: `eslint-plugin-supabase-security`
|
|
155
|
+
- `@modelcontextprotocol/*`: `eslint-plugin-mcp-sdk-security`
|
|
156
|
+
- `openai`, `@openai/agents`: `eslint-plugin-openai-security`
|
|
157
|
+
- `@anthropic-ai/sdk`, `@anthropic-ai/claude-agent-sdk`: `eslint-plugin-anthropic-security`
|
|
158
|
+
- `@google/genai`: `eslint-plugin-gemini-security`
|
|
159
|
+
- `ai`: `eslint-plugin-vercel-ai-security`
|
|
160
|
+
- `aws-lambda`, `@types/aws-lambda`, `@middy/core`: `eslint-plugin-lambda-security`
|
|
161
|
+
|
|
162
|
+
The full stack-to-plugin playbook (with config rendering and a proof step) is the `security-linting` skill: https://github.com/ofri-peretz/eslint/tree/main/skills/security-linting
|
|
163
|
+
|
|
164
|
+
## More
|
|
165
|
+
|
|
166
|
+
- Docs: https://eslint.interlace.tools/docs/security/plugin-browser-security
|
|
167
|
+
- README.md in this package: every rule with examples.
|
|
168
|
+
- `eslint-plugin-browser-security/oxlint` is an entry point for oxlint's JS plugin support; see the README.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-browser-security",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.1",
|
|
4
4
|
"description": "ESLint browser security and XSS rules — detects DOM XSS, postMessage abuse, tokens in localStorage, insecure cookies, clickjacking, mixed content, and CSP gaps.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -34,7 +34,8 @@
|
|
|
34
34
|
"files": [
|
|
35
35
|
"src/",
|
|
36
36
|
"README.md",
|
|
37
|
-
"LICENSE"
|
|
37
|
+
"LICENSE",
|
|
38
|
+
"AGENTS.md"
|
|
38
39
|
],
|
|
39
40
|
"keywords": [
|
|
40
41
|
"eslint",
|
package/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"no-innerhtml"(){return require("./rules/no-innerhtml").noInnerhtml},get"no-eval"(){return require("./rules/no-eval").noEval},get"require-postmessage-origin-check"(){return require("./rules/require-postmessage-origin-check").requirePostmessageOriginCheck},get"no-postmessage-wildcard-origin"(){return require("./rules/no-postmessage-wildcard-origin").noPostmessageWildcardOrigin},get"no-postmessage-innerhtml"(){return require("./rules/no-postmessage-innerhtml").noPostmessageInnerhtml},get"no-sensitive-localstorage"(){return require("./rules/no-sensitive-localstorage").noSensitiveLocalstorage},get"no-jwt-in-storage"(){return require("./rules/no-jwt-in-storage").noJwtInStorage},get"no-sensitive-sessionstorage"(){return require("./rules/no-sensitive-sessionstorage").noSensitiveSessionstorage},get"no-sensitive-indexeddb"(){return require("./rules/no-sensitive-indexeddb").noSensitiveIndexeddb},get"no-sensitive-cookie-js"(){return require("./rules/no-sensitive-cookie-js").noSensitiveCookieJs},get"no-cookie-auth-tokens"(){return require("./rules/no-cookie-auth-tokens").noCookieAuthTokens},get"require-cookie-secure-attrs"(){return require("./rules/require-cookie-secure-attrs").requireCookieSecureAttrs},get"require-websocket-wss"(){return require("./rules/require-websocket-wss").requireWebsocketWss},get"no-websocket-innerhtml"(){return require("./rules/no-websocket-innerhtml").noWebsocketInnerhtml},get"no-websocket-eval"(){return require("./rules/no-websocket-eval").noWebsocketEval},get"no-filereader-innerhtml"(){return require("./rules/no-filereader-innerhtml").noFilereaderInnerhtml},get"require-blob-url-revocation"(){return require("./rules/require-blob-url-revocation").requireBlobUrlRevocation},get"no-dynamic-service-worker-url"(){return require("./rules/no-dynamic-service-worker-url").noDynamicServiceWorkerUrl},get"no-worker-message-innerhtml"(){return require("./rules/no-worker-message-innerhtml").noWorkerMessageInnerhtml},get"no-unsafe-inline-csp"(){return require("./rules/no-unsafe-inline-csp").noUnsafeInlineCsp},get"no-unsafe-eval-csp"(){return require("./rules/no-unsafe-eval-csp").noUnsafeEvalCsp},get"detect-mixed-content"(){return require("./rules/detect-mixed-content").detectMixedContent},get"no-allow-arbitrary-loads"(){return require("./rules/no-allow-arbitrary-loads").noAllowArbitraryLoads},get"no-clickjacking"(){return require("./rules/no-clickjacking").noClickjacking},get"no-credentials-in-query-params"(){return require("./rules/no-credentials-in-query-params").noCredentialsInQueryParams},get"no-http-urls"(){return require("./rules/no-http-urls").noHttpUrls},get"no-incomplete-url-sanitization"(){return require("./rules/no-incomplete-url-sanitization").noIncompleteUrlSanitization},get"no-insecure-redirects"(){return require("./rules/no-insecure-redirects").noInsecureRedirects},get"no-insecure-websocket"(){return require("./rules/no-insecure-websocket").noInsecureWebsocket},get"no-missing-cors-check"(){return require("./rules/no-missing-cors-check").noMissingCorsCheck},get"no-missing-csrf-protection"(){return require("./rules/no-missing-csrf-protection").noMissingCsrfProtection},get"no-missing-security-headers"(){return require("./rules/no-missing-security-headers").noMissingSecurityHeaders},get"no-password-in-url"(){return require("./rules/no-password-in-url").noPasswordInUrl},get"no-permissive-cors"(){return require("./rules/no-permissive-cors").noPermissiveCors},get"no-sensitive-data-in-analytics"(){return require("./rules/no-sensitive-data-in-analytics").noSensitiveDataInAnalytics},get"no-sensitive-data-in-cache"(){return require("./rules/no-sensitive-data-in-cache").noSensitiveDataInCache},get"no-tracking-without-consent"(){return require("./rules/no-tracking-without-consent").noTrackingWithoutConsent},get"no-unencrypted-transmission"(){return require("./rules/no-unencrypted-transmission").noUnencryptedTransmission},get"no-unescaped-url-parameter"(){return require("./rules/no-unescaped-url-parameter").noUnescapedUrlParameter},get"no-unvalidated-deeplinks"(){return require("./rules/no-unvalidated-deeplinks").noUnvalidatedDeeplinks},get"require-csp-headers"(){return require("./rules/require-csp-headers").requireCspHeaders},get"require-https-only"(){return require("./rules/require-https-only").requireHttpsOnly},get"require-url-validation"(){return require("./rules/require-url-validation").requireUrlValidation},get"require-mime-type-validation"(){return require("./rules/require-mime-type-validation").requireMimeTypeValidation},get"no-disabled-certificate-validation"(){return require("./rules/no-disabled-certificate-validation").noDisabledCertificateValidation},get"no-client-side-auth-logic"(){return require("./rules/no-client-side-auth-logic").noClientSideAuthLogic}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-browser-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-browser-security",version:"3.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"no-innerhtml"(){return require("./rules/no-innerhtml").noInnerhtml},get"no-eval"(){return require("./rules/no-eval").noEval},get"require-postmessage-origin-check"(){return require("./rules/require-postmessage-origin-check").requirePostmessageOriginCheck},get"no-postmessage-wildcard-origin"(){return require("./rules/no-postmessage-wildcard-origin").noPostmessageWildcardOrigin},get"no-postmessage-innerhtml"(){return require("./rules/no-postmessage-innerhtml").noPostmessageInnerhtml},get"no-sensitive-localstorage"(){return require("./rules/no-sensitive-localstorage").noSensitiveLocalstorage},get"no-jwt-in-storage"(){return require("./rules/no-jwt-in-storage").noJwtInStorage},get"no-sensitive-sessionstorage"(){return require("./rules/no-sensitive-sessionstorage").noSensitiveSessionstorage},get"no-sensitive-indexeddb"(){return require("./rules/no-sensitive-indexeddb").noSensitiveIndexeddb},get"no-sensitive-cookie-js"(){return require("./rules/no-sensitive-cookie-js").noSensitiveCookieJs},get"no-cookie-auth-tokens"(){return require("./rules/no-cookie-auth-tokens").noCookieAuthTokens},get"require-cookie-secure-attrs"(){return require("./rules/require-cookie-secure-attrs").requireCookieSecureAttrs},get"require-websocket-wss"(){return require("./rules/require-websocket-wss").requireWebsocketWss},get"no-websocket-innerhtml"(){return require("./rules/no-websocket-innerhtml").noWebsocketInnerhtml},get"no-websocket-eval"(){return require("./rules/no-websocket-eval").noWebsocketEval},get"no-filereader-innerhtml"(){return require("./rules/no-filereader-innerhtml").noFilereaderInnerhtml},get"require-blob-url-revocation"(){return require("./rules/require-blob-url-revocation").requireBlobUrlRevocation},get"no-dynamic-service-worker-url"(){return require("./rules/no-dynamic-service-worker-url").noDynamicServiceWorkerUrl},get"no-worker-message-innerhtml"(){return require("./rules/no-worker-message-innerhtml").noWorkerMessageInnerhtml},get"no-unsafe-inline-csp"(){return require("./rules/no-unsafe-inline-csp").noUnsafeInlineCsp},get"no-unsafe-eval-csp"(){return require("./rules/no-unsafe-eval-csp").noUnsafeEvalCsp},get"detect-mixed-content"(){return require("./rules/detect-mixed-content").detectMixedContent},get"no-allow-arbitrary-loads"(){return require("./rules/no-allow-arbitrary-loads").noAllowArbitraryLoads},get"no-clickjacking"(){return require("./rules/no-clickjacking").noClickjacking},get"no-credentials-in-query-params"(){return require("./rules/no-credentials-in-query-params").noCredentialsInQueryParams},get"no-http-urls"(){return require("./rules/no-http-urls").noHttpUrls},get"no-incomplete-url-sanitization"(){return require("./rules/no-incomplete-url-sanitization").noIncompleteUrlSanitization},get"no-insecure-redirects"(){return require("./rules/no-insecure-redirects").noInsecureRedirects},get"no-insecure-websocket"(){return require("./rules/no-insecure-websocket").noInsecureWebsocket},get"no-missing-cors-check"(){return require("./rules/no-missing-cors-check").noMissingCorsCheck},get"no-missing-csrf-protection"(){return require("./rules/no-missing-csrf-protection").noMissingCsrfProtection},get"no-missing-security-headers"(){return require("./rules/no-missing-security-headers").noMissingSecurityHeaders},get"no-password-in-url"(){return require("./rules/no-password-in-url").noPasswordInUrl},get"no-permissive-cors"(){return require("./rules/no-permissive-cors").noPermissiveCors},get"no-sensitive-data-in-analytics"(){return require("./rules/no-sensitive-data-in-analytics").noSensitiveDataInAnalytics},get"no-sensitive-data-in-cache"(){return require("./rules/no-sensitive-data-in-cache").noSensitiveDataInCache},get"no-tracking-without-consent"(){return require("./rules/no-tracking-without-consent").noTrackingWithoutConsent},get"no-unencrypted-transmission"(){return require("./rules/no-unencrypted-transmission").noUnencryptedTransmission},get"no-unescaped-url-parameter"(){return require("./rules/no-unescaped-url-parameter").noUnescapedUrlParameter},get"no-unvalidated-deeplinks"(){return require("./rules/no-unvalidated-deeplinks").noUnvalidatedDeeplinks},get"require-csp-headers"(){return require("./rules/require-csp-headers").requireCspHeaders},get"require-https-only"(){return require("./rules/require-https-only").requireHttpsOnly},get"require-url-validation"(){return require("./rules/require-url-validation").requireUrlValidation},get"require-mime-type-validation"(){return require("./rules/require-mime-type-validation").requireMimeTypeValidation},get"no-disabled-certificate-validation"(){return require("./rules/no-disabled-certificate-validation").noDisabledCertificateValidation},get"no-client-side-auth-logic"(){return require("./rules/no-client-side-auth-logic").noClientSideAuthLogic}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-browser-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-browser-security",version:"3.1.1"},rules:exports.rules};const recommendedRules={"browser-security/no-innerhtml":"error","browser-security/no-eval":"error","browser-security/require-postmessage-origin-check":"error","browser-security/no-postmessage-wildcard-origin":"error","browser-security/no-postmessage-innerhtml":"error","browser-security/no-sensitive-localstorage":"error","browser-security/no-jwt-in-storage":"error","browser-security/no-sensitive-sessionstorage":"error","browser-security/no-sensitive-indexeddb":"error","browser-security/no-sensitive-cookie-js":"error","browser-security/no-cookie-auth-tokens":"error","browser-security/require-cookie-secure-attrs":"error","browser-security/require-websocket-wss":"error","browser-security/no-websocket-innerhtml":"error","browser-security/no-websocket-eval":"error","browser-security/no-filereader-innerhtml":"error","browser-security/require-blob-url-revocation":"warn","browser-security/no-dynamic-service-worker-url":"error","browser-security/no-worker-message-innerhtml":"error","browser-security/no-unsafe-inline-csp":"error","browser-security/no-unsafe-eval-csp":"error","browser-security/detect-mixed-content":"error","browser-security/no-unencrypted-transmission":"error","browser-security/no-allow-arbitrary-loads":"error","browser-security/no-credentials-in-query-params":"error","browser-security/no-http-urls":"error","browser-security/no-incomplete-url-sanitization":"error","browser-security/no-insecure-redirects":"error","browser-security/no-disabled-certificate-validation":"error","browser-security/require-https-only":"error","browser-security/no-insecure-websocket":"error","browser-security/no-unvalidated-deeplinks":"error","browser-security/no-client-side-auth-logic":"error"};exports.configs={flagship:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/no-postmessage-wildcard-origin":"error"}},recommended:{plugins:{"browser-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"browser-security":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`browser-security/${ruleName}`,"error"]))},xss:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/no-innerhtml":"error","browser-security/no-eval":"error"}},storage:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/no-sensitive-localstorage":"error"}},postmessage:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/require-postmessage-origin-check":"error","browser-security/no-postmessage-wildcard-origin":"error"}},websocket:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/require-websocket-wss":"error"}},cookies:{plugins:{"browser-security":exports.plugin},rules:{"browser-security/no-sensitive-cookie-js":"error"}}};exports.default=exports.plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCredentialsInQueryParams=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const WHOLE_NAME_CREDENTIALS=new Set(["token","auth"]);const DEFAULT_CREDENTIAL_SUFFIXES=["password","passwd","pwd","passphrase","secret","apikey","api key","access token","refresh token","id token","auth token","session token","bearer token","private token"];function isCredentialParam(name,suffixes){const words=(0,eslint_devkit_1.identifierWords)(name);if(WHOLE_NAME_CREDENTIALS.has(words.join(" ")))return true;return suffixes.some(suffix=>suffix.length<=words.length&&suffix.every((word,i)=>words[words.length-suffix.length+i]===word))}const QUERY_PARAMETER=/[?&]([^=&?#\s\u0001]+)=/g;const DEFAULT_BODY_PROPERTIES=["body","data","form","formData"];exports.noCredentialsInQueryParams=(0,eslint_devkit_1.createRule)({name:"no-credentials-in-query-params",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-credentials-in-query-params.md",description:"Disallow credentials in URL query parameters",cwe:"CWE-598",cvss:9.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Credentials in Query Parameters",cwe:"CWE-598",description:"Credentials detected in URL query
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCredentialsInQueryParams=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const WHOLE_NAME_CREDENTIALS=new Set(["token","auth"]);const DEFAULT_CREDENTIAL_SUFFIXES=["password","passwd","pwd","passphrase","secret","apikey","api key","access token","refresh token","id token","auth token","session token","bearer token","private token"];function isCredentialParam(name,suffixes){const words=(0,eslint_devkit_1.identifierWords)(name);if(WHOLE_NAME_CREDENTIALS.has(words.join(" ")))return true;return suffixes.some(suffix=>suffix.length<=words.length&&suffix.every((word,i)=>words[words.length-suffix.length+i]===word))}const QUERY_PARAMETER=/[?&]([^=&?#\s\u0001]+)=/g;const DEFAULT_BODY_PROPERTIES=["body","data","form","formData"];exports.noCredentialsInQueryParams=(0,eslint_devkit_1.createRule)({name:"no-credentials-in-query-params",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-credentials-in-query-params.md",description:"Disallow credentials in URL query parameters",cwe:"CWE-598",cvss:9.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Credentials in Query Parameters",cwe:"CWE-598",description:"Credentials detected in URL query parameter `{{param}}` - this is a security risk",severity:"CRITICAL",fix:"Use secure methods: POST body, headers (Authorization), or secure cookies",documentationLink:"https://cwe.mitre.org/data/definitions/598.html"})},schema:[{type:"object",properties:{bodyProperties:{type:"array",items:{type:"string"},default:DEFAULT_BODY_PROPERTIES,description:"Property names whose value is a request body rather than a URL"},credentialSuffixes:{type:"array",items:{type:"string"},default:[...DEFAULT_CREDENTIAL_SUFFIXES],description:"Credential words a query-parameter name ends in (replaces the default)"}},additionalProperties:false}]},defaultOptions:[{bodyProperties:DEFAULT_BODY_PROPERTIES,credentialSuffixes:[...DEFAULT_CREDENTIAL_SUFFIXES]}],createOnce(context){let bodyPropertyNames;let credentialSuffixWords;const OUT_OF_BAND_FLOWS=/\/(reset|reset-password|forgot|verify|verify-email|confirm|activate|unsubscribe|magic-?link)\b/;function reportableCredential(url){const match=[...url.matchAll(QUERY_PARAMETER)].find(([,name])=>isCredentialParam(name,credentialSuffixWords)&&!(name.toLowerCase()==="token"&&OUT_OF_BAND_FLOWS.test(url)));return match===void 0?null:match[1]}function isRequestBody(node){const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===node&&!parent.computed){const key=(0,eslint_devkit_1.objectKeyName)(parent);if(key!==null&&bodyPropertyNames.has(key))return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&parent.callee.name==="URLSearchParams"){return true}return false}function report(node,param){context.report({node,messageId:"violationDetected",data:{param}})}return{before(){const{bodyProperties=DEFAULT_BODY_PROPERTIES,credentialSuffixes=DEFAULT_CREDENTIAL_SUFFIXES}=context.options[0]??{};bodyPropertyNames=new Set(bodyProperties);credentialSuffixWords=credentialSuffixes.map(eslint_devkit_1.identifierWords)},Literal(node){if(typeof node.value==="string"){const param=reportableCredential(node.value);if(param!==null&&!isRequestBody(node))report(node,param)}},TemplateLiteral(node){const INTERPOLATION="";const text=node.quasis.map(q=>q.value.raw).join(INTERPOLATION);const param=reportableCredential(text);if(param!==null&&!isRequestBody(node))report(node,param)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeInlineCsp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noUnsafeInlineCsp=(0,eslint_devkit_1.createRule)({name:"no-unsafe-inline-csp",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unsafe-inline-csp.md",description:"Disallow 'unsafe-inline' in Content Security Policy",cwe:"CWE-79",cvss:7.5},messages:{unsafeInline:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP 'unsafe-inline' Detected",cwe:"CWE-79",owasp:"A03:2021",cvss:7.5,description:"'unsafe-inline' in CSP allows inline scripts
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeInlineCsp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DIRECTIVE_NAME=/^(?:default|script|style|img|connect|font|frame|media|object|worker|child|manifest|prefetch|base|form)-(?:src|uri|action)(?:-elem|-attr)?$/i;const SCRIPT_DIRECTIVES=new Set(["script-src","script-src-elem","script-src-attr"]);const STYLE_DIRECTIVES=new Set(["style-src","style-src-elem","style-src-attr"]);function inlineEnables(value){const policies=value.split(",").map(policyEnables);return{named:policies.some(policy=>policy.named),script:policies.some(policy=>policy.script),style:policies.some(policy=>policy.style)}}function policyEnables(policy){const directives=policy.split(";").flatMap(segment=>{const tokens=segment.split(/[\s"<>=]+/).filter(Boolean);const at=tokens.findIndex(token=>DIRECTIVE_NAME.test(token));if(at===-1)return[];return[{name:tokens[at].toLowerCase(),inline:tokens.slice(at+1).some(token=>token.toLowerCase()==="'unsafe-inline'")}]});const names=new Set(directives.map(directive=>directive.name));const enables=(governing,own)=>directives.some(directive=>directive.inline&&(governing.has(directive.name)||directive.name==="default-src"&&!names.has(own)));return{named:directives.length>0,script:enables(SCRIPT_DIRECTIVES,"script-src"),style:enables(STYLE_DIRECTIVES,"style-src")}}exports.noUnsafeInlineCsp=(0,eslint_devkit_1.createRule)({name:"no-unsafe-inline-csp",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-unsafe-inline-csp.md",description:"Disallow 'unsafe-inline' in Content Security Policy",cwe:"CWE-79",cvss:7.5},messages:{unsafeInline:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP 'unsafe-inline' Detected",cwe:"CWE-79",owasp:"A03:2021",cvss:7.5,description:"'unsafe-inline' in a script-governing CSP directive allows inline scripts to execute, defeating XSS protection.",severity:"HIGH",fix:"Use nonces or hashes instead: script-src 'nonce-abc123' or script-src 'sha256-...'",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP"}),unsafeInlineStyle:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP 'unsafe-inline' for Styles",cwe:"CWE-79",owasp:"A03:2021",cvss:4.3,description:"'unsafe-inline' in style-src allows inline styles, which an injected <style> or style attribute can use for CSS injection (data exfiltration through selectors, UI redressing).",severity:"MEDIUM",fix:"Move styles to stylesheets, or allow them by nonce or hash: style-src 'nonce-abc123'",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},checkStyleSrc:{type:"boolean",default:false,description:"Also report 'unsafe-inline' that permits inline styles, under a MEDIUM-severity message."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,checkStyleSrc:false}],createOnce(context,currentOptions){const UNSAFE_INLINE_PATTERN=/'unsafe-inline'/i;let checkStyleSrc;const isCspName=name=>/^content-security-policy(-report-only)?$/i.test(name)||/^contentsecuritypolicy(reportonly)?$/i.test(name)||name.toLowerCase()==="csp";function atCspSink(node){const parent=node.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[1]===node){const first=parent.arguments[0];return first.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof first.value==="string"&&isCspName(first.value)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===node){const keyText=(0,eslint_devkit_1.objectKeyName)(parent);return keyText!==null&&isCspName(keyText)}const attribute=parent.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute?parent:parent.parent;if(attribute?.type!==eslint_devkit_1.AST_NODE_TYPES.JSXAttribute||attribute.name.type!==eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier||attribute.name.name!=="content"){return false}const element=attribute.parent;return element.attributes.some(other=>other.type===eslint_devkit_1.AST_NODE_TYPES.JSXAttribute&&other.name.type===eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier&&/^http-?equiv$/i.test(other.name.name)&&other.value?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof other.value.value==="string"&&isCspName(other.value.value))}const SOURCE_EXPRESSION=/^(?:'[^'\s]+'|[a-z][a-z0-9+.-]*:|[a-z][a-z0-9+.-]*:\/\/\S+|\*(?:\.\S+)?)$/i;const grants=value=>value.trim().split(/\s+/).every(token=>SOURCE_EXPRESSION.test(token));function checkForUnsafeInline(node,value){if(!UNSAFE_INLINE_PATTERN.test(value))return;const enabled=inlineEnables(value);if(enabled.named){if(enabled.script){context.report({node,messageId:"unsafeInline"})}else if(checkStyleSrc&&enabled.style){context.report({node,messageId:"unsafeInlineStyle"})}return}if(atCspSink(node)&&grants(value)){context.report({node,messageId:"unsafeInline"})}}return{before(){const[options={}]=currentOptions();const{allowInTests}=options;({checkStyleSrc=false}=options);const filename=context.filename;const isTestFile=(0,eslint_devkit_1.isTestFilePath)(filename);if(allowInTests&&isTestFile){return false}return true},Literal(node){if(typeof node.value==="string"){checkForUnsafeInline(node,node.value)}},TemplateLiteral(node){const value=node.quasis.map(q=>q.value.raw).join("");checkForUnsafeInline(node,value)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requirePostmessageOriginCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const regexp_anchoring_1=require("../../utils/regexp-anchoring");const resolve_binding_1=require("../../utils/resolve-binding");const NON_WINDOW_RECEIVERS=new Set(["WebSocket","EventSource","Worker","SharedWorker","BroadcastChannel","MessagePort","MessageChannel"]);function receiverKey(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"){const name=node.property.type==="PrivateIdentifier"?`#${node.property.name}`:(0,eslint_devkit_1.propertyName)(node);if(name===null)return void 0;if(node.object.type==="ThisExpression"){return`this.${name}`}if(node.object.type==="Identifier"){return`${node.object.name}.${name}`}}return void 0}const GLOBAL_RECEIVERS=new Set(["window","self","globalThis"]);function isMembershipReceiver(node,sourceCode){if((0,eslint_devkit_1.staticString)(node)!==null)return false;if(node.type==="Identifier"){return(0,eslint_devkit_1.staticString)((0,resolve_binding_1.resolveInitializer)(node,sourceCode))===null}return true}function fieldKey(node){if(node.key.type==="PrivateIdentifier")return`this.#${node.key.name}`;const name=(0,eslint_devkit_1.objectKeyName)(node);return name===null?void 0:`this.${name}`}function annotatedTypeName(annotation){const type=annotation?.typeAnnotation;if(type?.type==="TSTypeReference"&&type.typeName.type==="Identifier"){return type.typeName.name}return void 0}function hasOriginCheck(node,sourceCode){const text=sourceCode.getText(node);const originPatterns=[/origin\s*[!=]==?/,/checkOrigin/i,/validateOrigin/i,/isAllowedOrigin/i,/trustedOrigins/i,/allowedOrigins/i];return originPatterns.some(pattern=>pattern.test(text))}function isMessageEvent(node){return(0,eslint_devkit_1.staticString)(node.arguments[0])==="message"}exports.requirePostmessageOriginCheck=(0,eslint_devkit_1.createRule)({name:"require-postmessage-origin-check",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-postmessage-origin-check.md",description:"Require origin validation in postMessage event listeners",cwe:"CWE-346",cvss:7.5},messages:{missingOriginCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing postMessage Origin Validation",cwe:"CWE-346",description:"postMessage listener lacks origin check. Malicious sites can send messages that will be processed.",severity:"HIGH",fix:"Add origin validation: if (event.origin !== 'https://trusted-domain.com') return;",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let sourceCode;let unverified;let nonWindowReceivers;let anchoredOriginTests;function rememberIfNonWindow(key,typeName){if(key===void 0||typeName===void 0)return;if(NON_WINDOW_RECEIVERS.has(typeName))nonWindowReceivers.add(key)}function isOriginRead(node){return node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="origin"}return{before(){const[options={}]=currentOptions();const{allowInTests}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return false}sourceCode=context.sourceCode;unverified=[];nonWindowReceivers=new Set;anchoredOriginTests=[];return true},PropertyDefinition(node){rememberIfNonWindow(fieldKey(node),annotatedTypeName(node.typeAnnotation))},VariableDeclarator(node){if(node.id.type!=="Identifier")return;rememberIfNonWindow(node.id.name,annotatedTypeName(node.id.typeAnnotation))},NewExpression(node){if(node.callee.type!=="Identifier")return;const typeName=node.callee.name;const parent=node.parent;if(parent.type==="VariableDeclarator"){rememberIfNonWindow(receiverKey(parent.id),typeName);return}if(parent.type==="AssignmentExpression"){rememberIfNonWindow(receiverKey(parent.left),typeName);return}if(parent.type==="PropertyDefinition"){rememberIfNonWindow(fieldKey(parent),typeName)}},CallExpression(node){const callee=node.callee;if(node.arguments.length===1&&isOriginRead(node.arguments[0])&&((0,regexp_anchoring_1.isAnchoredRegexpTest)(node,sourceCode)||callee.type==="MemberExpression"&&((0,eslint_devkit_1.propertyName)(callee)==="includes"||(0,eslint_devkit_1.propertyName)(callee)==="has")&&isMembershipReceiver(callee.object,sourceCode))){anchoredOriginTests.push([node.range[0],node.range[1]])}let isMessageListener=false;let receiver;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="addEventListener"){if(isMessageEvent(node)){isMessageListener=true;receiver=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requirePostmessageOriginCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const regexp_anchoring_1=require("../../utils/regexp-anchoring");const resolve_binding_1=require("../../utils/resolve-binding");const NON_WINDOW_RECEIVERS=new Set(["WebSocket","EventSource","Worker","SharedWorker","BroadcastChannel","MessagePort","MessageChannel"]);function receiverKey(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"){const name=node.property.type==="PrivateIdentifier"?`#${node.property.name}`:(0,eslint_devkit_1.propertyName)(node);if(name===null)return void 0;if(node.object.type==="ThisExpression"){return`this.${name}`}if(node.object.type==="Identifier"){return`${node.object.name}.${name}`}}return void 0}const GLOBAL_RECEIVERS=new Set(["window","self","globalThis"]);const GLOBAL_KEY="<global>";const WORKER_ENTRY=/\.worker\.[cm]?[jt]sx?$/;const SERVICE_WORKER_EVENTS=new Set(["install","activate","fetch","push","pushsubscriptionchange","sync","notificationclick","notificationclose"]);function declaredVariable(identifier,sourceCode){for(let scope=sourceCode.getScope(identifier);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(variable!==void 0)return variable.defs.length>0?variable:void 0}return void 0}function globalAwareKey(node,sourceCode){if(node.type==="Identifier"&&(node.name==="self"||node.name==="globalThis")&&declaredVariable(node,sourceCode)===void 0){return GLOBAL_KEY}return receiverKey(node)}function isMembershipReceiver(node,sourceCode){if((0,eslint_devkit_1.staticString)(node)!==null)return false;if(node.type==="Identifier"){return(0,eslint_devkit_1.staticString)((0,resolve_binding_1.resolveInitializer)(node,sourceCode))===null}return true}function fieldKey(node){if(node.key.type==="PrivateIdentifier")return`this.#${node.key.name}`;const name=(0,eslint_devkit_1.objectKeyName)(node);return name===null?void 0:`this.${name}`}function annotatedTypeName(annotation){const type=annotation?.typeAnnotation;if(type?.type==="TSTypeReference"&&type.typeName.type==="Identifier"){return type.typeName.name}return void 0}function hasOriginCheck(node,sourceCode){const text=sourceCode.getText(node);const originPatterns=[/origin\s*[!=]==?/,/checkOrigin/i,/validateOrigin/i,/isAllowedOrigin/i,/trustedOrigins/i,/allowedOrigins/i];return originPatterns.some(pattern=>pattern.test(text))}function isMessageEvent(node){return(0,eslint_devkit_1.staticString)(node.arguments[0])==="message"}exports.requirePostmessageOriginCheck=(0,eslint_devkit_1.createRule)({name:"require-postmessage-origin-check",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/require-postmessage-origin-check.md",description:"Require origin validation in postMessage event listeners",cwe:"CWE-346",cvss:7.5},messages:{missingOriginCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing postMessage Origin Validation",cwe:"CWE-346",description:"postMessage listener lacks origin check. Malicious sites can send messages that will be processed.",severity:"HIGH",fix:"Add origin validation: if (event.origin !== 'https://trusted-domain.com') return;",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#security_concerns"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let sourceCode;let unverified;let nonWindowReceivers;let serviceWorkerScopes;let anchoredOriginTests;function rememberIfNonWindow(key,typeName){if(key===void 0||typeName===void 0)return;if(NON_WINDOW_RECEIVERS.has(typeName))nonWindowReceivers.add(key)}function aliasesWindow(identifier){const init=(0,resolve_binding_1.resolveInitializer)(identifier,sourceCode);return init?.type==="Identifier"&&init.name==="window"}function isOriginRead(node){return node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="origin"}return{before(){const[options={}]=currentOptions();const{allowInTests}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return false}sourceCode=context.sourceCode;unverified=[];nonWindowReceivers=new Set;serviceWorkerScopes=new Set;anchoredOriginTests=[];if(WORKER_ENTRY.test(filename))nonWindowReceivers.add(GLOBAL_KEY);return true},PropertyDefinition(node){rememberIfNonWindow(fieldKey(node),annotatedTypeName(node.typeAnnotation))},VariableDeclarator(node){if(node.id.type!=="Identifier")return;rememberIfNonWindow(node.id.name,annotatedTypeName(node.id.typeAnnotation))},NewExpression(node){if(node.callee.type!=="Identifier")return;const typeName=node.callee.name;const parent=node.parent;if(parent.type==="VariableDeclarator"){rememberIfNonWindow(receiverKey(parent.id),typeName);return}if(parent.type==="AssignmentExpression"){rememberIfNonWindow(receiverKey(parent.left),typeName);return}if(parent.type==="PropertyDefinition"){rememberIfNonWindow(fieldKey(parent),typeName)}},CallExpression(node){const callee=node.callee;if(node.arguments.length===1&&isOriginRead(node.arguments[0])&&((0,regexp_anchoring_1.isAnchoredRegexpTest)(node,sourceCode)||callee.type==="MemberExpression"&&((0,eslint_devkit_1.propertyName)(callee)==="includes"||(0,eslint_devkit_1.propertyName)(callee)==="has")&&isMembershipReceiver(callee.object,sourceCode))){anchoredOriginTests.push([node.range[0],node.range[1]])}let isMessageListener=false;let receiver;let receiverBinding;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="addEventListener"){const eventName=(0,eslint_devkit_1.staticString)(node.arguments[0]);const key=globalAwareKey(callee.object,sourceCode);const binding=callee.object.type==="Identifier"?declaredVariable(callee.object,sourceCode):void 0;if(eventName!==null&&SERVICE_WORKER_EVENTS.has(eventName)){if(key===GLOBAL_KEY)nonWindowReceivers.add(GLOBAL_KEY);else if(binding!==void 0&&!aliasesWindow(callee.object))serviceWorkerScopes.add(binding)}if(isMessageEvent(node)){isMessageListener=true;receiver=key;receiverBinding=binding;if(callee.object.type==="NewExpression"&&callee.object.callee.type==="Identifier"&&NON_WINDOW_RECEIVERS.has(callee.object.callee.name)){return}}}if(callee.type==="Identifier"&&callee.name==="addEventListener"){const eventName=(0,eslint_devkit_1.staticString)(node.arguments[0]);if(eventName!==null&&SERVICE_WORKER_EVENTS.has(eventName)){nonWindowReceivers.add(GLOBAL_KEY)}if(eventName==="message"){isMessageListener=true;receiver=GLOBAL_KEY}}if(!isMessageListener){return}const handlerArg=node.arguments[1];if(!handlerArg){return}if(handlerArg.type==="FunctionExpression"||handlerArg.type==="ArrowFunctionExpression"){if(!hasOriginCheck(handlerArg,sourceCode)){unverified.push({handler:handlerArg,receiver,binding:receiverBinding})}}},AssignmentExpression(node){const target=node.left;const onGlobal=target.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(target)==="onmessage"&&target.object.type==="Identifier"&&GLOBAL_RECEIVERS.has(target.object.name):target.type==="Identifier"&&target.name==="onmessage";const handler=node.right;if(onGlobal&&(handler.type==="FunctionExpression"||handler.type==="ArrowFunctionExpression")&&!hasOriginCheck(handler,sourceCode)){unverified.push({handler,receiver:target.type==="MemberExpression"?globalAwareKey(target.object,sourceCode):GLOBAL_KEY})}},"Program:exit"(){for(const{handler,receiver,binding}of unverified){if(nonWindowReceivers.has(receiver)){continue}if(binding!==void 0&&serviceWorkerScopes.has(binding)){continue}const guarded=anchoredOriginTests.some(([start,end])=>start>=handler.range[0]&&end<=handler.range[1]);if(guarded)continue;context.report({node:handler,messageId:"missingOriginCheck"})}}}}});
|