tabsmith-lint 0.3.0 → 0.5.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.
package/README.md CHANGED
@@ -24,8 +24,10 @@ Chrome reviewers flag:
24
24
  | Violation ID | What it means | tabsmith rules |
25
25
  |---|---|---|
26
26
  | Purple Potassium | Excessive / unused permissions | PERM001, PERM003, PERM004, PERM005 |
27
- | Blue Argon | Remotely hosted code / string execution / forbidden CSP | MV3001, MV3002, MV3004 |
27
+ | Blue Argon | Remotely hosted code / latent remote loaders / string execution / forbidden CSP | MV3001, MV3005, MV3002, MV3004 |
28
28
  | Yellow Magnesium | Functionality / broken packaging | FUNC001, FUNC002 |
29
+ | Red Titanium | Obfuscated code (minification is fine) | OBF001 |
30
+ | Harmful / unexpected behavior | DNR rules that strip sites' security headers | SEC001 |
29
31
 
30
32
  ```bash
31
33
  npx tabsmith-lint ./my-extension
@@ -82,15 +84,46 @@ exists, leave the severity at `fix`.
82
84
 
83
85
  ## Status
84
86
 
85
- Chrome-only, directory input, 11 rules (PERM001-005, MV3001-004, FUNC001-002).
87
+ Chrome-only, directory input, 14 rules (PERM001-005, MV3001-005, FUNC001-002, SEC001, OBF001).
86
88
 
87
89
  MV3001 (remotely hosted code, `reject`) covers HTML `<script src="https://…">`, remote
88
- `import`/`import()`, remote `importScripts()`, and a remote `src` set on a
90
+ `import`/`import()`, remote `importScripts()`, a remote `src` set on a
89
91
  `document.createElement("script")` element (`.src =`, `setAttribute("src", …)`,
90
- `Object.assign(…, { src })`). Fetching remote JSON/data with `fetch`/XHR is not
92
+ `Object.assign(…, { src })`), and remote entries in
93
+ `chrome.scripting.executeScript({ files })` / `registerContentScripts([{ js }])` /
94
+ `updateContentScripts`. Fetching remote JSON/data with `fetch`/XHR is not
91
95
  remotely hosted code and is never flagged; neither are `img`/`iframe` sources or
92
96
  computed URLs.
93
97
 
98
+ MV3005 (latent remote-code loader) covers what MV3001 deliberately leaves out: bundled
99
+ code that *could* load a remote script. A `<script>` element (or `importScripts`) given
100
+ a computed `src` is `fix` when the URL is built on a remote prefix
101
+ (`"https://cdn/" + v`, including a prefix held in a variable bound only to that string,
102
+ `var base = "https://cdn/"; s.src = base + "x.js"`) or the same file also contains a
103
+ remote `.js`/`.mjs` URL literal;
104
+ the finding names the URL and, when a banner or `vendor/` path identifies it, the
105
+ bundled package. Other remote `.js` URL literals in shipped code are `info` (they never
106
+ change the verdict). Only `.js`/`.mjs` URLs count, so remote JSON/data endpoints are
107
+ never flagged.
108
+
109
+ SEC001 (DNR security-header stripping) reads static `declarative_net_request` rulesets
110
+ and literal `updateDynamicRules`/`updateSessionRules` rules, and flags `modifyHeaders`
111
+ that `remove`/`set` `Content-Security-Policy`(-Report-Only), `X-Frame-Options`,
112
+ `Cross-Origin-Opener/Embedder/Resource-Policy` or `Strict-Transport-Security`. It is
113
+ `fix` when the condition isn't scoped to specific domains and the extension has broad
114
+ host access, otherwise `info`.
115
+
116
+ OBF001 (obfuscated code, Red Titanium, `fix`) looks for fingerprints that minifiers
117
+ never produce: `_0x`-style hexadecimal identifiers in quantity, javascript-obfuscator's
118
+ string-array rotator and hex-index lookups, Dean Edwards' `eval(function(p,a,c,k,e,d)…)`
119
+ packer, `eval`/`Function` run on a decoded string (`eval(atob(…))`,
120
+ `new Function(String.fromCharCode(…))`), and plain-text strings spelled with `\x`/`\u`
121
+ escapes. One finding per file, naming the bundled package from its license banner,
122
+ `node_modules/` or `vendor/` path, or the bundler's module comment. Measured precision:
123
+ 0 findings on 43 popular npm browser packages (lodash, react-dom, vue, chart.js, three,
124
+ pdf.js, @babel/standalone, crypto libraries, ... — 12,041 script files), the 7 minified
125
+ release extensions and the Google samples; 37 of 38 obfuscated samples flagged.
126
+
94
127
  Firefox/Edge, ZIP/CRX input, SARIF, and a GitHub Action are on the roadmap.
95
128
 
96
129
  Two rules are intentionally conservative in v0.1 (trust is the product): **PERM001**
package/dist/cli.js CHANGED
@@ -24,7 +24,11 @@ Point it at an unpacked extension directory and it flags likely Chrome Web Store
24
24
  rejection risks before you submit:
25
25
  - unused / excessive permissions (the "Purple Potassium" rejection)
26
26
  - Manifest V3 violations: remotely hosted code (script tags, injected <script> src,
27
- import, importScripts), string execution, forbidden extension-page CSP, Manifest V2
27
+ import, importScripts, chrome.scripting remote files), latent remote-code loaders
28
+ in bundled code, string execution, forbidden extension-page CSP, Manifest V2
29
+ - declarativeNetRequest rules that strip security headers (CSP, X-Frame-Options, ...)
30
+ - obfuscated code ("Red Titanium": javascript-obfuscator output, packers, eval of
31
+ decoded strings), naming the bundled package it comes from; minified code is fine
28
32
  - broken packaging: missing or wrong-case file references
29
33
 
30
34
  ${USAGE}
@@ -1,5 +1,8 @@
1
1
  import { loadManifest } from "./manifest.js";
2
- import { discoverFiles, isScript, isHtml } from "./file-discovery.js";
2
+ import { discoverFiles, isScript, isHtml, isWithinRoot, refToRelPath } from "./file-discovery.js";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { stripBom } from "./source-lines.js";
3
6
  import { collectManifestRefs } from "./manifest-refs.js";
4
7
  import { parseScript } from "../parse/parse-script.js";
5
8
  import { extractFromScripts } from "../parse/extract-api-calls.js";
@@ -33,6 +36,7 @@ export function analyze(rootDir, options) {
33
36
  hostAccessSignals,
34
37
  manifestRefs: manifestRefs.all,
35
38
  runtimeRequestedPermissions: extraction.runtimeRequestedPermissions,
39
+ dnrRulesets: loadDnrRulesets(rootDir, manifest),
36
40
  };
37
41
  const ruleFindings = runRules(model);
38
42
  const parseFindings = scriptFiles
@@ -86,3 +90,36 @@ function deriveHostSignals(apiCalls) {
86
90
  }
87
91
  return out;
88
92
  }
93
+ /** Read static DNR rulesets named in the manifest. Paths outside the package,
94
+ * missing files and invalid JSON are skipped here (FUNC001 reports missing files). */
95
+ function loadDnrRulesets(rootDir, manifest) {
96
+ const resources = manifest.declarative_net_request?.rule_resources;
97
+ if (!Array.isArray(resources))
98
+ return [];
99
+ const out = [];
100
+ for (const rs of resources) {
101
+ if (typeof rs?.path !== "string")
102
+ continue;
103
+ const rel = refToRelPath(rs.path);
104
+ if (!isWithinRoot(rootDir, rel))
105
+ continue;
106
+ const abs = join(rootDir, rel);
107
+ try {
108
+ if (!existsSync(abs) || !statSync(abs).isFile())
109
+ continue;
110
+ const content = stripBom(readFileSync(abs, "utf8"));
111
+ let rules = null;
112
+ try {
113
+ rules = JSON.parse(content);
114
+ }
115
+ catch {
116
+ rules = null;
117
+ }
118
+ out.push({ relPath: rel, id: typeof rs.id === "string" ? rs.id : undefined, enabled: rs.enabled !== false, content, rules });
119
+ }
120
+ catch {
121
+ continue;
122
+ }
123
+ }
124
+ return out;
125
+ }
@@ -2,7 +2,9 @@ import { SEVERITY_RANK } from "../engine/verdict.js";
2
2
  import { permissionRules } from "./permissions.js";
3
3
  import { mv3Rules } from "./mv3.js";
4
4
  import { fileRules } from "./files.js";
5
- export const allRules = [...permissionRules, ...mv3Rules, ...fileRules];
5
+ import { securityRules } from "./security.js";
6
+ import { obfuscationRules } from "./obfuscation.js";
7
+ export const allRules = [...permissionRules, ...mv3Rules, ...fileRules, ...securityRules, ...obfuscationRules];
6
8
  /** Run every rule and return all findings, ordered reject → fix → info. */
7
9
  export function runRules(model) {
8
10
  const findings = allRules.flatMap((rule) => rule(model));
package/dist/rules/mv3.js CHANGED
@@ -11,7 +11,8 @@ import { findLine, findLineByIndex } from "../engine/source-lines.js";
11
11
  export const MV3002_SEVERITY = "fix";
12
12
  const REMOTE_SCRIPT_RE = /<script[^>]*\bsrc\s*=\s*["']((?:https?:)?\/\/[^"']+)["']/gi;
13
13
  /** MV3001 — remotely hosted code (HTML remote <script src>, remote import/import(),
14
- * importScripts, and remote src on a JS-created <script> element). */
14
+ * importScripts, remote src on a JS-created <script> element, and remote entries
15
+ * in chrome.scripting.executeScript({files}) / registerContentScripts({js})). */
15
16
  function mv3001(model) {
16
17
  const findings = [];
17
18
  for (const html of model.htmlFiles) {
@@ -55,6 +56,7 @@ function mv3001(model) {
55
56
  }
56
57
  });
57
58
  findings.push(...injectedRemoteScripts(script.relPath, script.ast));
59
+ findings.push(...remoteScriptingFiles(script.relPath, script.ast));
58
60
  }
59
61
  return findings;
60
62
  }
@@ -117,20 +119,31 @@ function patternNames(pattern, out = []) {
117
119
  }
118
120
  return out;
119
121
  }
120
- /** Names bound ONLY to document.createElement("script") anywhere in the file. */
121
- function scriptElementNames(ast) {
122
- const script = new Set();
122
+ /** Names whose EVERY binding in the file is a value accepted by `valueOf` (all
123
+ * bindings agreeing on that value). Any parameter, other initializer, reassignment,
124
+ * update or conflicting value with the same name drops it — reused/minified names
125
+ * are skipped, never guessed. */
126
+ function namesBoundOnlyTo(ast, valueOf) {
127
+ const bound = new Map();
123
128
  const other = new Set();
129
+ const record = (name, v) => {
130
+ if (bound.has(name) && bound.get(name) !== v)
131
+ other.add(name);
132
+ else
133
+ bound.set(name, v);
134
+ };
124
135
  walk(ast, (node) => {
125
136
  if (node.type === "VariableDeclarator") {
126
- if (node.id?.type === "Identifier" && isScriptCreate(node.init))
127
- script.add(node.id.name);
137
+ const v = node.id?.type === "Identifier" && node.init ? valueOf(node.init) : null;
138
+ if (v !== null)
139
+ record(node.id.name, v);
128
140
  else if (node.init)
129
141
  patternNames(node.id).forEach((n) => other.add(n));
130
142
  }
131
143
  else if (node.type === "AssignmentExpression" && node.left?.type === "Identifier") {
132
- if (node.operator === "=" && isScriptCreate(node.right))
133
- script.add(node.left.name);
144
+ const v = node.operator === "=" ? valueOf(node.right) : null;
145
+ if (v !== null)
146
+ record(node.left.name, v);
134
147
  else
135
148
  other.add(node.left.name);
136
149
  }
@@ -163,44 +176,43 @@ function scriptElementNames(ast) {
163
176
  }
164
177
  });
165
178
  for (const n of other)
166
- script.delete(n);
167
- return script;
179
+ bound.delete(n);
180
+ return bound;
168
181
  }
169
- function injectedRemoteScripts(file, ast) {
182
+ /** Names bound ONLY to document.createElement("script") anywhere in the file. */
183
+ function scriptElementNames(ast) {
184
+ return new Set(namesBoundOnlyTo(ast, (init) => (isScriptCreate(init) ? true : null)).keys());
185
+ }
186
+ /** Names bound ONLY to one string literal (e.g. `var base = "https://cdn.example/"`). */
187
+ function constStringNames(ast) {
188
+ return namesBoundOnlyTo(ast, (init) => staticString(init));
189
+ }
190
+ /** Every place a `document.createElement("script")` element gets its `src` set,
191
+ * literal or not: `.src =`, `["src"] =`, `setAttribute("src", …)`,
192
+ * `Object.assign(el, { src })`. Shared by MV3001 (literal remote URL) and
193
+ * MV3005 (computed URL = latent loader). */
194
+ function scriptSrcSets(ast) {
170
195
  const names = scriptElementNames(ast);
171
196
  const isScriptEl = (node) => isScriptCreate(node) || (node?.type === "Identifier" && names.has(node.name));
172
- const findings = [];
173
- const report = (node, url, how) => findings.push({
174
- ruleId: "MV3001",
175
- severity: "reject",
176
- confidence: "high",
177
- title: "Remotely hosted code injected via a <script> element",
178
- message: `${how} points a dynamically created <script> element at "${url}", which loads and runs remote code. Manifest V3 forbids remotely hosted code.`,
179
- file,
180
- line: node.loc?.start.line,
181
- column: node.loc?.start.column,
182
- chromeViolationId: "Blue Argon",
183
- fixHint: "Bundle the script in the extension package and inject the packaged copy (chrome.runtime.getURL(...) or chrome.scripting.executeScript({ files: [...] })). Fetching remote JSON/data is allowed; only executing remote code is Blue Argon.",
184
- });
197
+ const out = [];
185
198
  walk(ast, (node) => {
186
- // <el>.src = "https://…" / <el>["src"] = "https://…"
199
+ // <el>.src = … / <el>["src"] = …
187
200
  if (node.type === "AssignmentExpression" && node.operator === "=" && node.left?.type === "MemberExpression") {
188
201
  const left = node.left;
189
202
  const prop = left.computed ? staticString(left.property) : left.property?.type === "Identifier" ? left.property.name : null;
190
- const url = staticString(node.right);
191
- if (prop === "src" && isRemote(url) && isScriptEl(left.object))
192
- report(node, url, ".src assignment");
203
+ if (prop === "src" && isScriptEl(left.object))
204
+ out.push({ node, value: node.right, how: ".src assignment" });
193
205
  }
194
206
  if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed) {
195
207
  const method = node.callee.property?.type === "Identifier" ? node.callee.property.name : null;
196
- // <el>.setAttribute("src", "https://…")
208
+ // <el>.setAttribute("src", …)
197
209
  if (method === "setAttribute" && isScriptEl(node.callee.object)) {
198
210
  const attr = staticString(node.arguments?.[0]);
199
- const url = staticString(node.arguments?.[1]);
200
- if (attr?.toLowerCase() === "src" && isRemote(url))
201
- report(node, url, 'setAttribute("src")');
211
+ if (attr?.toLowerCase() === "src" && node.arguments?.[1]) {
212
+ out.push({ node, value: node.arguments[1], how: 'setAttribute("src")' });
213
+ }
202
214
  }
203
- // Object.assign(<el>, { src: "https://…" })
215
+ // Object.assign(<el>, { src: … })
204
216
  if (method === "assign" &&
205
217
  node.callee.object?.type === "Identifier" &&
206
218
  node.callee.object.name === "Object" &&
@@ -212,14 +224,106 @@ function injectedRemoteScripts(file, ast) {
212
224
  if (p.type !== "ObjectProperty")
213
225
  continue;
214
226
  const key = p.computed ? staticString(p.key) : p.key?.type === "Identifier" ? p.key.name : staticString(p.key);
215
- const url = staticString(p.value);
216
- if (key === "src" && isRemote(url))
217
- report(node, url, "Object.assign({ src })");
227
+ if (key === "src")
228
+ out.push({ node, value: p.value, how: "Object.assign({ src })" });
218
229
  }
219
230
  }
220
231
  }
221
232
  }
222
233
  });
234
+ return out;
235
+ }
236
+ function injectedRemoteScripts(file, ast) {
237
+ const findings = [];
238
+ for (const { node, value, how } of scriptSrcSets(ast)) {
239
+ const url = staticString(value);
240
+ if (!isRemote(url))
241
+ continue;
242
+ findings.push({
243
+ ruleId: "MV3001",
244
+ severity: "reject",
245
+ confidence: "high",
246
+ title: "Remotely hosted code injected via a <script> element",
247
+ message: `${how} points a dynamically created <script> element at "${url}", which loads and runs remote code. Manifest V3 forbids remotely hosted code.`,
248
+ file,
249
+ line: node.loc?.start.line,
250
+ column: node.loc?.start.column,
251
+ chromeViolationId: "Blue Argon",
252
+ fixHint: "Bundle the script in the extension package and inject the packaged copy (chrome.runtime.getURL(...) or chrome.scripting.executeScript({ files: [...] })). Fetching remote JSON/data is allowed; only executing remote code is Blue Argon.",
253
+ });
254
+ }
255
+ return findings;
256
+ }
257
+ // --- chrome.scripting with remote files ------------------------------------
258
+ // `chrome.scripting.executeScript({ files: ["https://…"] })` and
259
+ // `chrome.scripting.registerContentScripts([{ js: ["https://…"] }])` (also
260
+ // updateContentScripts, and the browser.* namespace) name remote code as the
261
+ // thing to inject. Only literal http(s):// or protocol-relative entries are
262
+ // judged; local paths and computed entries are left alone. CSS entries are not
263
+ // code and are not judged.
264
+ const SCRIPTING_METHODS = new Set(["executeScript", "registerContentScripts", "updateContentScripts"]);
265
+ function scriptingMethod(callee) {
266
+ if (callee?.type !== "MemberExpression" && callee?.type !== "OptionalMemberExpression")
267
+ return null;
268
+ if (callee.computed || callee.property?.type !== "Identifier" || !SCRIPTING_METHODS.has(callee.property.name))
269
+ return null;
270
+ const obj = callee.object;
271
+ if ((obj?.type !== "MemberExpression" && obj?.type !== "OptionalMemberExpression") || obj.computed)
272
+ return null;
273
+ if (obj.property?.type !== "Identifier" || obj.property.name !== "scripting")
274
+ return null;
275
+ return callee.property.name;
276
+ }
277
+ function objectProp(obj, name) {
278
+ if (obj?.type !== "ObjectExpression")
279
+ return undefined;
280
+ for (const p of obj.properties ?? []) {
281
+ if (p.type !== "ObjectProperty")
282
+ continue;
283
+ const key = p.computed ? staticString(p.key) : p.key?.type === "Identifier" ? p.key.name : staticString(p.key);
284
+ if (key === name)
285
+ return p.value;
286
+ }
287
+ return undefined;
288
+ }
289
+ function remoteScriptingFiles(file, ast) {
290
+ const findings = [];
291
+ walk(ast, (node) => {
292
+ if (node.type !== "CallExpression" && node.type !== "OptionalCallExpression")
293
+ return;
294
+ const method = scriptingMethod(node.callee);
295
+ if (!method)
296
+ return;
297
+ const arg = node.arguments?.[0];
298
+ const lists = [];
299
+ if (method === "executeScript")
300
+ lists.push(objectProp(arg, "files"));
301
+ else if (arg?.type === "ArrayExpression")
302
+ for (const el of arg.elements ?? [])
303
+ lists.push(objectProp(el, "js"));
304
+ for (const list of lists) {
305
+ if (list?.type !== "ArrayExpression")
306
+ continue;
307
+ for (const el of list.elements ?? []) {
308
+ const url = staticString(el);
309
+ if (!isRemote(url))
310
+ continue;
311
+ const key = method === "executeScript" ? "files" : "js";
312
+ findings.push({
313
+ ruleId: "MV3001",
314
+ severity: "reject",
315
+ confidence: "high",
316
+ title: "Remotely hosted code passed to chrome.scripting",
317
+ message: `scripting.${method}() lists "${url}" in ${key}, which injects code from a remote URL. Manifest V3 forbids remotely hosted code (and Chrome only accepts files packaged with the extension here).`,
318
+ file,
319
+ line: el.loc?.start.line ?? node.loc?.start.line,
320
+ column: el.loc?.start.column,
321
+ chromeViolationId: "Blue Argon",
322
+ fixHint: `Bundle the script in the extension package and list its packaged path in ${key} (e.g. "scripts/content.js").`,
323
+ });
324
+ }
325
+ }
326
+ });
223
327
  return findings;
224
328
  }
225
329
  function isRemote(v) {
@@ -262,6 +366,157 @@ function remoteImport(file, node, url, via = "import") {
262
366
  : "Bundle the dependency inside the extension package instead of importing it remotely.",
263
367
  };
264
368
  }
369
+ // --- MV3005: latent remote-code loaders ------------------------------------
370
+ // Review judges what bundled code *could* do, not just what it does by default
371
+ // (e.g. a shared widget that can inject an rrweb recorder <script> it never
372
+ // uses still drew a Blue Argon rejection). MV3005 surfaces that tier without
373
+ // condemning it, so it ships at `fix` / `info`, never `reject`:
374
+ // (a) `fix`: a createElement("script") element (or importScripts) is given a
375
+ // COMPUTED src, and either the expression starts with a remote URL prefix
376
+ // (`"https://cdn/" + v`, `` `https://cdn/${v}.js` ``) or the same file also
377
+ // contains a remote `.js`/`.mjs` URL string literal;
378
+ // (b) `info`: remote `.js`/`.mjs` URL string literals in shipped JS that no
379
+ // MV3001/MV3005 finding already explains (one finding per file).
380
+ // Precision: only URLs whose path ends in .js/.mjs count, so remote JSON/data
381
+ // endpoints, images and pages are never flagged; chrome.runtime.getURL(...)
382
+ // sources are local; literal remote srcs are MV3001's job.
383
+ const REMOTE_JS_RE = /^(?:https?:)?\/\/[^\s"'`<>()]+\.m?js(?:[?#][^\s"'`<>]*)?$/i;
384
+ // Links to a source-code *page* (GitHub/GitLab/Bitbucket blob/tree views) are documentation, not scripts.
385
+ const SOURCE_VIEWER_RE = /^(?:https?:)?\/\/(?:www\.)?(?:github\.com|gitlab\.com|bitbucket\.org)\/[^?#]*\/(?:blob|tree|src)\//i;
386
+ function isRemoteJsUrl(v) {
387
+ return typeof v === "string" && v.length < 2048 && REMOTE_JS_RE.test(v) && !SOURCE_VIEWER_RE.test(v);
388
+ }
389
+ /** chrome|browser.runtime.getURL(...) / .extension.getURL(...) → a packaged file. */
390
+ function isGetUrlCall(node) {
391
+ if (node?.type !== "CallExpression")
392
+ return false;
393
+ const c = node.callee;
394
+ return (c?.type === "MemberExpression" && !c.computed &&
395
+ c.property?.type === "Identifier" && c.property.name === "getURL" &&
396
+ c.object?.type === "MemberExpression" && !c.object.computed &&
397
+ c.object.property?.type === "Identifier" &&
398
+ (c.object.property.name === "runtime" || c.object.property.name === "extension"));
399
+ }
400
+ /** Leading static text of a string-building expression ("a" + x, `a${x}`). With
401
+ * `consts`, a leading identifier bound only to one string literal resolves to it
402
+ * (`var base = "https://cdn/"; base + "x.js"`, `` `${base}x.js` ``). */
403
+ function staticPrefix(node, consts) {
404
+ if (node?.type === "StringLiteral")
405
+ return node.value;
406
+ if (node?.type === "Identifier")
407
+ return consts?.get(node.name) ?? null;
408
+ if (node?.type === "TemplateLiteral") {
409
+ const head = node.quasis?.[0]?.value?.cooked ?? null;
410
+ if (head === "" && node.expressions?.length)
411
+ return staticPrefix(node.expressions[0], consts);
412
+ return head;
413
+ }
414
+ if (node?.type === "BinaryExpression" && node.operator === "+")
415
+ return staticPrefix(node.left, consts);
416
+ return null;
417
+ }
418
+ const BANNER_RE = /^\s*(?:\/\*[!*]?|\/\/)\s*(?:@license\s+)?(@?[A-Za-z][\w./-]*)\s+v?(\d+\.\d+\.\d+[\w.-]*)/;
419
+ const VENDOR_DIR_RE = /(?:^|\/)(?:vendor|vendors|third[_-]?party|lib|libs)\/([^/]+?)(?:\.min)?\.m?js$/i;
420
+ /** Best-effort name of the bundled package a file comes from (banner or vendor path). */
421
+ export function probablePackage(relPath, content) {
422
+ const b = BANNER_RE.exec(content.slice(0, 1000));
423
+ if (b)
424
+ return `${b[1]}@${b[2]}`;
425
+ const v = VENDOR_DIR_RE.exec(relPath);
426
+ return v ? v[1] : null;
427
+ }
428
+ function remoteJsLiterals(ast) {
429
+ const out = [];
430
+ walk(ast, (node) => {
431
+ const v = node.type === "StringLiteral" || node.type === "TemplateLiteral" ? staticString(node) : null;
432
+ if (isRemoteJsUrl(v))
433
+ out.push({ url: v, line: node.loc?.start.line });
434
+ });
435
+ return out;
436
+ }
437
+ function mv3005(model) {
438
+ const findings = [];
439
+ const explained = new Set(); // file\0url already covered by MV3001
440
+ for (const f of mv3001(model)) {
441
+ if (!f.file)
442
+ continue;
443
+ for (const m of f.message.matchAll(/"([^"]+)"/g))
444
+ explained.add(`${f.file}\0${m[1]}`);
445
+ }
446
+ for (const script of model.scriptFiles) {
447
+ if (!script.ast)
448
+ continue;
449
+ const file = script.relPath;
450
+ const literals = remoteJsLiterals(script.ast).filter((l) => !explained.has(`${file}\0${l.url}`));
451
+ const urls = [...new Set(literals.map((l) => l.url))];
452
+ const pkg = probablePackage(file, script.content);
453
+ const from = pkg ? ` This file looks like bundled code from ${pkg}.` : "";
454
+ const list = (u) => u.slice(0, 3).map((x) => `"${x}"`).join(", ") + (u.length > 3 ? ` (+${u.length - 3} more)` : "");
455
+ const sinks = scriptSrcSets(script.ast).filter((s) => staticString(s.value) === null);
456
+ walk(script.ast, (node) => {
457
+ if (node.type === "CallExpression" && isImportScriptsCallee(node.callee)) {
458
+ for (const arg of node.arguments ?? []) {
459
+ if (staticString(arg) === null && arg.type !== "SpreadElement")
460
+ sinks.push({ node, value: arg, how: "importScripts()" });
461
+ }
462
+ }
463
+ });
464
+ // One `fix` finding per file (first loader), other loader lines listed, to keep bundles readable.
465
+ let latent = false;
466
+ const hits = [];
467
+ const consts = sinks.length ? constStringNames(script.ast) : undefined;
468
+ const prefixes = new Set(); // remote prefixes already reported by a fix finding
469
+ for (const { node, value, how } of sinks) {
470
+ if (isGetUrlCall(value))
471
+ continue;
472
+ const prefix = staticPrefix(value, consts);
473
+ if (isRemote(prefix)) {
474
+ prefixes.add(prefix);
475
+ const msg = value.type === "Identifier"
476
+ ? `${how} loads a script from the variable ${value.name}, which only ever holds the remote URL (remote prefix) "${prefix}".`
477
+ : `${how} loads a script from a URL built at runtime on the remote prefix "${prefix}".`;
478
+ hits.push({ node, message: `${msg} Even if this path never runs, reviewers treat it as remotely hosted code.` });
479
+ }
480
+ else if (urls.length > 0) {
481
+ latent = true;
482
+ hits.push({ node, message: `${how} loads a script from a computed URL, and this file also contains the remote script URL ${list(urls)}. Review checks what bundled code could do, so this latent loader can draw a Blue Argon rejection even if it never runs.` });
483
+ }
484
+ }
485
+ if (hits.length > 0) {
486
+ hits.sort((a, b) => (a.node.loc?.start.index ?? 0) - (b.node.loc?.start.index ?? 0));
487
+ const first = hits[0];
488
+ const more = [...new Set(hits.slice(1).map((h) => h.node.loc?.start.line).filter((l) => l !== undefined && l !== first.node.loc?.start.line))];
489
+ const also = more.length ? ` Other script loads in this file: line${more.length > 1 ? "s" : ""} ${more.slice(0, 10).join(", ")}${more.length > 10 ? ", …" : ""}.` : "";
490
+ findings.push({
491
+ ruleId: "MV3005",
492
+ severity: "fix",
493
+ confidence: "medium",
494
+ title: "Latent remote-code loader",
495
+ message: first.message + also + from,
496
+ file,
497
+ line: first.node.loc?.start.line,
498
+ column: first.node.loc?.start.column,
499
+ chromeViolationId: "Blue Argon",
500
+ fixHint: "If the extension never needs this loader, strip or stub it at build time (or configure the package not to include it) and mention it in the submission notes. If it is needed, bundle the script and load the packaged copy via chrome.runtime.getURL(...). Fetching remote JSON/data is fine.",
501
+ });
502
+ }
503
+ const unexplained = urls.filter((u) => !prefixes.has(u));
504
+ if (!latent && unexplained.length > 0) {
505
+ findings.push({
506
+ ruleId: "MV3005",
507
+ severity: "info",
508
+ confidence: "low",
509
+ title: "Remote script URL in shipped code",
510
+ message: `Shipped code contains the remote script URL ${list(unexplained)}. No loader was found for it, but reviewers search bundles for remote .js URLs; check that nothing can load it.${from}`,
511
+ file,
512
+ line: literals.find((l) => !prefixes.has(l.url))?.line,
513
+ chromeViolationId: "Blue Argon",
514
+ fixHint: "Remove unused remote script URLs at build time, or explain them in the submission notes.",
515
+ });
516
+ }
517
+ }
518
+ return findings;
519
+ }
265
520
  const STRING_TIMERS = new Set(["setTimeout", "setInterval"]);
266
521
  /** MV3002 — string execution (eval, new Function, string-form timers). */
267
522
  function mv3002(model) {
@@ -390,4 +645,4 @@ function mv3004(model) {
390
645
  fixHint: "Remove the remote origins and 'unsafe-*' keywords; bundle code locally. If eval is unavoidable, move that code to a sandboxed page (content_security_policy.sandbox).",
391
646
  }];
392
647
  }
393
- export const mv3Rules = [mv3001, mv3002, mv3003, mv3004];
648
+ export const mv3Rules = [mv3001, mv3002, mv3003, mv3004, mv3005];
@@ -0,0 +1,327 @@
1
+ import { walk } from "../parse/parse-script.js";
2
+ import { findLineByIndex } from "../engine/source-lines.js";
3
+ // OBF001 — obfuscated code (Chrome Web Store "Red Titanium"). Google's policy:
4
+ // minification is allowed, obfuscation is not ("character encoding", hidden
5
+ // functionality, packers). Minified bundles look nothing like obfuscator output,
6
+ // so OBF001 only fires on fingerprints that minifiers never produce:
7
+ // - `_0x`-style hexadecimal identifiers (javascript-obfuscator / obfuscator.io)
8
+ // used in quantity;
9
+ // - a string-array rotator: `arr.push(arr.shift())` inside a function that also
10
+ // runs the obfuscator's parseInt checksum or a `while (--n)` countdown;
11
+ // - string-array lookups: one function called over and over with a hex numeric
12
+ // literal (`_0x1a2b(0x1f4)`), the decoder call that replaces every string;
13
+ // - a Dean Edwards packer: `eval(function(p,a,c,k,e,d){…}(…))`;
14
+ // - eval / Function run on a decoded payload: `eval(atob(…))`,
15
+ // `new Function(String.fromCharCode(…))`, `eval(unescape(…))`;
16
+ // - plain-ASCII text hidden behind escapes: many string literals written as
17
+ // `"\x68\x65\x6c\x6c\x6f"` (minifiers only escape non-printable/non-ASCII).
18
+ // Thresholds were set on a negative set of 40+ popular minified npm libraries
19
+ // (lodash, react-dom, vue, chart.js, three, pdf.js, @babel/standalone, crypto
20
+ // libraries, ...) plus the minified release corpus, where OBF001 reports nothing.
21
+ // Severity is `fix`, not `reject`: the finding names what to replace and is a
22
+ // strong signal, but static fingerprints cannot prove intent. One finding per file.
23
+ export const OBF001_SEVERITY = "fix";
24
+ /** Minimum distinct `_0x…` identifiers for the identifier signal. */
25
+ export const HEX_IDENT_MIN = 10;
26
+ /** Minimum calls of a single function with a small hex index literal argument… */
27
+ export const HEX_LOOKUP_MIN = 25;
28
+ /** …with at least this many distinct index values. */
29
+ export const HEX_LOOKUP_DISTINCT_MIN = 15;
30
+ /** Minimum string literals that are plain ASCII text spelled with escapes. */
31
+ export const ESCAPED_ASCII_MIN = 20;
32
+ const HEX_IDENT_RE = /^_0x[0-9a-f]{3,}$/i;
33
+ const DECODERS = new Set(["atob", "unescape", "decodeURIComponent", "decodeURI", "escape"]);
34
+ function propName(member) {
35
+ if (member?.type !== "MemberExpression" && member?.type !== "OptionalMemberExpression")
36
+ return null;
37
+ if (!member.computed)
38
+ return member.property?.type === "Identifier" ? member.property.name : null;
39
+ return member.property?.type === "StringLiteral" ? member.property.value : null;
40
+ }
41
+ /** `A.push(A.shift())` / `A['push'](A['shift']())` with the same identifier A. */
42
+ function isPushShift(node) {
43
+ if (node?.type !== "CallExpression" || propName(node.callee) !== "push")
44
+ return false;
45
+ const obj = node.callee.object;
46
+ const arg = node.arguments?.[0];
47
+ if (obj?.type !== "Identifier" || node.arguments.length !== 1)
48
+ return false;
49
+ return (arg?.type === "CallExpression" &&
50
+ propName(arg.callee) === "shift" &&
51
+ arg.callee.object?.type === "Identifier" &&
52
+ arg.callee.object.name === obj.name &&
53
+ (arg.arguments?.length ?? 0) === 0);
54
+ }
55
+ function isFunctionNode(node) {
56
+ return node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression" || node?.type === "ArrowFunctionExpression";
57
+ }
58
+ /** A function body that rotates an array AND runs a checksum (parseInt ×2) or a `while (--n)` countdown. */
59
+ function isRotatorFunction(fn) {
60
+ let pushShift = false;
61
+ let parseInts = 0;
62
+ let countdown = false;
63
+ walk(fn.body, (n) => {
64
+ if (isPushShift(n))
65
+ pushShift = true;
66
+ else if (n.type === "CallExpression" && n.callee?.type === "Identifier" && n.callee.name === "parseInt")
67
+ parseInts++;
68
+ else if (n.type === "WhileStatement" && n.test?.type === "UpdateExpression" && n.test.operator === "--")
69
+ countdown = true;
70
+ });
71
+ return pushShift && (parseInts >= 2 || countdown);
72
+ }
73
+ // String-array decoder call: `_0x1a2b(0x1f4)` / `_0x1a2b(0x1f4, "key")`. The index is
74
+ // a small, lower-case, unpadded hex literal (< 0x10000). Colour and hash constants
75
+ // (0xffb845, 0x428a2f98) are larger, so crypto/graphics code doesn't count.
76
+ const LOOKUP_HEX_RE = /^0x(?:0|[1-9a-f][0-9a-f]{0,3})$/;
77
+ function isHexLookup(node) {
78
+ if (node.callee?.type !== "Identifier")
79
+ return false;
80
+ const args = node.arguments ?? [];
81
+ if (args.length !== 1 && args.length !== 2)
82
+ return false;
83
+ if (args[0]?.type !== "NumericLiteral" || !LOOKUP_HEX_RE.test(args[0].extra?.raw ?? ""))
84
+ return false;
85
+ return args.length === 1 || ["StringLiteral", "NumericLiteral", "UnaryExpression"].includes(args[1]?.type);
86
+ }
87
+ /** `eval(function(p,a,c,k,e,d){…}(…))` — Dean Edwards' packer. */
88
+ function isPacker(node) {
89
+ if (node?.type !== "CallExpression" || node.callee?.type !== "Identifier" || node.callee.name !== "eval")
90
+ return false;
91
+ const inner = node.arguments?.[0];
92
+ if (inner?.type !== "CallExpression" || !isFunctionNode(inner.callee))
93
+ return false;
94
+ const names = (inner.callee.params ?? []).map((p) => (p.type === "Identifier" ? p.name : "?")).join(",");
95
+ return /^p,a,c,k,e,[a-z]$/.test(names);
96
+ }
97
+ /** A decoding call: atob(...), unescape(...), String.fromCharCode(...), possibly nested. */
98
+ function decoderName(node) {
99
+ if (node?.type !== "CallExpression")
100
+ return null;
101
+ const c = node.callee;
102
+ if (c?.type === "Identifier" && DECODERS.has(c.name))
103
+ return `${c.name}()`;
104
+ if ((c?.type === "MemberExpression") && propName(c) === "fromCharCode" &&
105
+ c.object?.type === "Identifier" && c.object.name === "String")
106
+ return "String.fromCharCode()";
107
+ return null;
108
+ }
109
+ /** eval(<decoded>), Function(<decoded>), new Function(<decoded>) → the decoder it wraps. */
110
+ function decodedEvalOf(node) {
111
+ const isCall = node?.type === "CallExpression" || node?.type === "NewExpression";
112
+ if (!isCall || node.callee?.type !== "Identifier")
113
+ return null;
114
+ const name = node.callee.name;
115
+ if (name !== "eval" && name !== "Function")
116
+ return null;
117
+ if (name === "eval" && node.type === "NewExpression")
118
+ return null;
119
+ // the code argument is the first for eval and the last for Function
120
+ const args = node.arguments ?? [];
121
+ const code = name === "eval" ? args[0] : args[args.length - 1];
122
+ const dec = decoderName(code);
123
+ return dec ? `${node.type === "NewExpression" ? "new " : ""}${name}(${dec})` : null;
124
+ }
125
+ const ESCAPE_RE = /\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\u\{[0-9a-fA-F]+\}/g;
126
+ /** A string literal whose source spells printable ASCII text with escapes ("\x68\x69"). */
127
+ function isEscapedAscii(node) {
128
+ if (node?.type !== "StringLiteral")
129
+ return false;
130
+ const raw = node.extra?.raw;
131
+ const value = node.value;
132
+ if (!raw || value.length < 3)
133
+ return false;
134
+ if (!/^[\x20-\x7e]+$/.test(value) || !/[A-Za-z]/.test(value))
135
+ return false;
136
+ let escapedChars = 0;
137
+ let escapes = 0;
138
+ for (const m of raw.matchAll(ESCAPE_RE)) {
139
+ const ch = m[0].startsWith("\\x") ? parseInt(m[0].slice(2), 16) : parseInt(m[0].replace(/[\\u{}]/g, ""), 16);
140
+ if (ch >= 0x20 && ch <= 0x7e) {
141
+ escapes++;
142
+ escapedChars += m[0].length;
143
+ }
144
+ }
145
+ return escapes >= 3 && escapedChars >= (raw.length - 2) * 0.75;
146
+ }
147
+ /** Raw obfuscation measurements for one parsed file (exported for tests and FP probes). */
148
+ export function obfuscationSignals(ast) {
149
+ const hexIds = new Set();
150
+ const lookups = new Map();
151
+ let rotator = false;
152
+ let packer = false;
153
+ let decodedEval = null;
154
+ let escapedAscii = 0;
155
+ let firstIndex = null;
156
+ const mark = (n) => {
157
+ const i = n?.start;
158
+ if (typeof i === "number" && (firstIndex === null || i < firstIndex))
159
+ firstIndex = i;
160
+ };
161
+ let firstHexId = null;
162
+ let firstEscaped = null;
163
+ const firstLookup = new Map();
164
+ const functions = [];
165
+ const pushShifts = [];
166
+ walk(ast, (node) => {
167
+ switch (node.type) {
168
+ case "Identifier":
169
+ if (HEX_IDENT_RE.test(node.name)) {
170
+ hexIds.add(node.name);
171
+ if (!firstHexId)
172
+ firstHexId = node;
173
+ }
174
+ break;
175
+ case "StringLiteral":
176
+ if (isEscapedAscii(node)) {
177
+ escapedAscii++;
178
+ if (!firstEscaped)
179
+ firstEscaped = node;
180
+ }
181
+ break;
182
+ case "FunctionDeclaration":
183
+ case "FunctionExpression":
184
+ case "ArrowFunctionExpression":
185
+ functions.push(node);
186
+ break;
187
+ case "CallExpression":
188
+ case "NewExpression": {
189
+ if (isPushShift(node))
190
+ pushShifts.push(node.start);
191
+ if (node.type === "CallExpression" && isPacker(node)) {
192
+ packer = true;
193
+ mark(node);
194
+ }
195
+ const de = decodedEvalOf(node);
196
+ if (de && !decodedEval) {
197
+ decodedEval = de;
198
+ mark(node);
199
+ }
200
+ if (node.type === "CallExpression" && isHexLookup(node)) {
201
+ const name = node.callee.name;
202
+ const e = lookups.get(name) ?? { calls: 0, values: new Set() };
203
+ e.calls++;
204
+ e.values.add(node.arguments[0].value);
205
+ lookups.set(name, e);
206
+ if (!firstLookup.has(name))
207
+ firstLookup.set(name, node);
208
+ }
209
+ break;
210
+ }
211
+ }
212
+ });
213
+ // Rotator check: only the INNERMOST function around each arr.push(arr.shift())
214
+ // (rare in real code; an outer bundle wrapper would contain unrelated parseInt calls).
215
+ for (const at of pushShifts) {
216
+ let inner = null;
217
+ for (const fn of functions)
218
+ if (fn.start < at && at < fn.end && (!inner || fn.start > inner.start))
219
+ inner = fn;
220
+ if (inner && isRotatorFunction(inner)) {
221
+ rotator = true;
222
+ mark(inner);
223
+ break;
224
+ }
225
+ }
226
+ let hexLookupCalls = 0;
227
+ let hexLookupCallee = null;
228
+ for (const [name, e] of lookups) {
229
+ // a decoder is called with many DIFFERENT indices; constant tables repeat a few values
230
+ if (e.values.size >= HEX_LOOKUP_DISTINCT_MIN && e.calls > hexLookupCalls) {
231
+ hexLookupCalls = e.calls;
232
+ hexLookupCallee = name;
233
+ }
234
+ }
235
+ if (hexIds.size >= HEX_IDENT_MIN)
236
+ mark(firstHexId);
237
+ if (hexLookupCalls >= HEX_LOOKUP_MIN)
238
+ mark(firstLookup.get(hexLookupCallee));
239
+ if (escapedAscii >= ESCAPED_ASCII_MIN)
240
+ mark(firstEscaped);
241
+ return {
242
+ hexIdentifiers: hexIds.size,
243
+ rotator,
244
+ hexLookupCalls,
245
+ hexLookupCallee,
246
+ packer,
247
+ decodedEval,
248
+ escapedAsciiStrings: escapedAscii,
249
+ firstIndex,
250
+ };
251
+ }
252
+ /** Human-readable list of the signals that crossed their thresholds (empty = not obfuscated). */
253
+ export function signalReasons(s) {
254
+ const out = [];
255
+ if (s.packer)
256
+ out.push("a Dean Edwards packer (eval(function(p,a,c,k,e,d){…}))");
257
+ if (s.decodedEval)
258
+ out.push(`code executed from a decoded string (${s.decodedEval})`);
259
+ if (s.rotator)
260
+ out.push("a string-array rotator (arr.push(arr.shift()) with a checksum loop)");
261
+ if (s.hexIdentifiers >= HEX_IDENT_MIN)
262
+ out.push(`${s.hexIdentifiers} _0x-style hexadecimal identifiers`);
263
+ if (s.hexLookupCalls >= HEX_LOOKUP_MIN)
264
+ out.push(`${s.hexLookupCalls} string-array lookups (${s.hexLookupCallee}(0x…))`);
265
+ if (s.escapedAsciiStrings >= ESCAPED_ASCII_MIN)
266
+ out.push(`${s.escapedAsciiStrings} plain-text strings spelled with \\x/\\u escapes`);
267
+ return out;
268
+ }
269
+ const BANNER_RE = /^\s*(?:\/\*[!*]?|\/\/)\s*(?:@license\s+)?(@?[A-Za-z][\w./-]*)\s+v?(\d+\.\d+\.\d+[\w.-]*)/;
270
+ const NODE_MODULES_RE = /(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)/g;
271
+ const VENDOR_RE = /(?:^|\/)(?:vendor|vendors|third[_-]?party|libs?)\/([^/]+?)(?:(?:\.min)?\.[cm]?js$|\/)/i;
272
+ // Module-path comments bundlers leave between modules: esbuild/rollup `// node_modules/x/index.js`,
273
+ // webpack `/***/ "./node_modules/x/index.js":` and `// CONCATENATED MODULE: ./src/a.js`.
274
+ const MODULE_MARKER_RE = /(?:^|\n)[ \t]*(?:\/\/|\/\*{1,3}\/)[ \t]*(?:CONCATENATED MODULE:[ \t]*)?["']?((?:\.{1,2}\/)?[\w@.+-]+(?:\/[\w@.+-]+)+\.[cm]?[jt]sx?)/g;
275
+ const PKG_IN_PATH_RE = /(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)\/(?!.*node_modules\/)/;
276
+ /** Best-effort name of the bundled npm package the obfuscated code comes from:
277
+ * a license banner, a node_modules/ path, a vendor/ path, or the nearest
278
+ * `node_modules/<pkg>` module-path comment before the obfuscated code in a bundle. */
279
+ export function bundledPackageName(relPath, content, index = null) {
280
+ const b = BANNER_RE.exec(content.slice(0, 1000));
281
+ if (b)
282
+ return `${b[1]}@${b[2]}`;
283
+ const nm = [...relPath.matchAll(NODE_MODULES_RE)];
284
+ if (nm.length)
285
+ return nm[nm.length - 1][1];
286
+ const v = VENDOR_RE.exec(relPath);
287
+ if (v)
288
+ return v[1];
289
+ if (index !== null && index > 0) {
290
+ const before = content.slice(Math.max(0, index - 200_000), index);
291
+ // Only the NEAREST module marker counts: if it is first-party (./src/...), don't blame a package.
292
+ const markers = [...before.matchAll(MODULE_MARKER_RE)];
293
+ const last = markers.length ? markers[markers.length - 1][1] : null;
294
+ const pkg = last ? PKG_IN_PATH_RE.exec(last) : null;
295
+ if (pkg)
296
+ return pkg[1];
297
+ }
298
+ return null;
299
+ }
300
+ function obf001(model) {
301
+ const findings = [];
302
+ for (const script of model.scriptFiles) {
303
+ if (!script.ast)
304
+ continue;
305
+ const s = obfuscationSignals(script.ast);
306
+ const reasons = signalReasons(s);
307
+ if (reasons.length === 0)
308
+ continue;
309
+ const pkg = bundledPackageName(script.relPath, script.content, s.firstIndex);
310
+ const from = pkg ? ` It looks like it comes from the bundled package ${pkg}.` : "";
311
+ findings.push({
312
+ ruleId: "OBF001",
313
+ severity: OBF001_SEVERITY,
314
+ confidence: reasons.length > 1 || s.packer || s.rotator ? "high" : "medium",
315
+ title: "Obfuscated code",
316
+ message: `This file shows obfuscation fingerprints: ${reasons.join("; ")}. The Chrome Web Store rejects obfuscated code (Red Titanium); minification is allowed, obfuscation is not.${from}`,
317
+ file: script.relPath,
318
+ line: s.firstIndex !== null ? findLineByIndex(script.content, s.firstIndex) : undefined,
319
+ chromeViolationId: "Red Titanium",
320
+ fixHint: pkg
321
+ ? `Replace ${pkg} with a non-obfuscated build (or another package), or ask its maintainer for readable source. Minified code is fine.`
322
+ : "Ship this code minified instead of obfuscated (drop javascript-obfuscator/packer steps from the build). Minified code is fine.",
323
+ });
324
+ }
325
+ return findings;
326
+ }
327
+ export const obfuscationRules = [obf001];
@@ -0,0 +1,179 @@
1
+ import { walk } from "../parse/parse-script.js";
2
+ import { findLine } from "../engine/source-lines.js";
3
+ // SEC001 — declarativeNetRequest `modifyHeaders` rules that remove or overwrite a
4
+ // page's security response headers (CSP, X-Frame-Options, COOP/COEP/CORP, HSTS).
5
+ // Stripping these on every site weakens the security of pages the user visits
6
+ // "whether or not the extension is in use", which Chrome Web Store reviewers and
7
+ // Trust & Safety treat as unexpected/harmful behavior. Deterministic from JSON
8
+ // already in the package, so precision is high; severity reflects reach:
9
+ // - `fix` when the rule's condition is not scoped to specific domains AND the
10
+ // extension has broad host access (modifyHeaders only applies where the
11
+ // extension has host permissions);
12
+ // - `info` when it is scoped (requestDomains/initiatorDomains/tabIds, a
13
+ // domain-anchored urlFilter or a regexFilter naming a domain) or the
14
+ // extension's host access is narrow.
15
+ // Sources: static rulesets (declarative_net_request.rule_resources) and literal
16
+ // rules passed to updateDynamicRules/updateSessionRules({ addRules: [...] }).
17
+ // `append` is not judged (appending a CSP only tightens it); request headers are
18
+ // out of scope.
19
+ export const SECURITY_HEADERS = new Set([
20
+ "content-security-policy",
21
+ "content-security-policy-report-only",
22
+ "x-frame-options",
23
+ "cross-origin-opener-policy",
24
+ "cross-origin-embedder-policy",
25
+ "cross-origin-resource-policy",
26
+ "strict-transport-security",
27
+ ]);
28
+ const JUDGED_OPS = new Set(["remove", "set"]);
29
+ const BROAD_HOST_RE = /^(<all_urls>|\*:\/\/\*\/\*|https?:\/\/\*\/\*|\*:\/\/\*\/|https?:\/\/\*\/)$/;
30
+ const DOMAIN_ANCHORED_RE = /^(\|\||\|https?:\/\/|https?:\/\/|\*:\/\/)(?!\*)[a-z0-9-]+(\.[a-z0-9-]+)+/i;
31
+ const REGEX_DOMAIN_RE = /[a-z0-9-]+\\\.[a-z]{2,}/i;
32
+ function strArr(v) {
33
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
34
+ }
35
+ function isScoped(cond) {
36
+ if (!cond || typeof cond !== "object")
37
+ return false;
38
+ if (strArr(cond.requestDomains).length || strArr(cond.initiatorDomains).length)
39
+ return true;
40
+ if (Array.isArray(cond.tabIds) && cond.tabIds.length)
41
+ return true;
42
+ if (typeof cond.urlFilter === "string" && DOMAIN_ANCHORED_RE.test(cond.urlFilter))
43
+ return true;
44
+ if (typeof cond.regexFilter === "string" && REGEX_DOMAIN_RE.test(cond.regexFilter))
45
+ return true;
46
+ return false;
47
+ }
48
+ function hasBroadHostAccess(model) {
49
+ const m = model.manifest;
50
+ const hosts = [...strArr(m.host_permissions), ...strArr(m.optional_host_permissions)];
51
+ if (model.manifest.manifest_version === 2)
52
+ hosts.push(...strArr(m.permissions));
53
+ return hosts.some((h) => BROAD_HOST_RE.test(h.trim()));
54
+ }
55
+ function describeCondition(cond) {
56
+ if (!cond || typeof cond !== "object" || Object.keys(cond).length === 0)
57
+ return "no condition (every request)";
58
+ if (typeof cond.urlFilter === "string")
59
+ return `urlFilter "${cond.urlFilter}"`;
60
+ if (typeof cond.regexFilter === "string")
61
+ return `regexFilter "${cond.regexFilter}"`;
62
+ if (strArr(cond.requestDomains).length)
63
+ return `requestDomains ${strArr(cond.requestDomains).slice(0, 3).join(", ")}`;
64
+ return "a condition with no URL or domain filter";
65
+ }
66
+ function judge(model, src, broadHosts) {
67
+ if (!Array.isArray(src.rules))
68
+ return [];
69
+ const out = [];
70
+ for (const rule of src.rules) {
71
+ if (!rule || typeof rule !== "object" || rule.action?.type !== "modifyHeaders")
72
+ continue;
73
+ const hits = (Array.isArray(rule.action.responseHeaders) ? rule.action.responseHeaders : []).filter((h) => typeof h?.header === "string" && SECURITY_HEADERS.has(h.header.toLowerCase()) && JUDGED_OPS.has(h.operation));
74
+ if (hits.length === 0)
75
+ continue;
76
+ const scoped = isScoped(rule.condition);
77
+ const severity = !scoped && broadHosts ? "fix" : "info";
78
+ const what = hits.map((h) => `${h.operation} ${h.header}`).join(", ");
79
+ const id = rule.id !== undefined ? ` ${rule.id}` : "";
80
+ const reach = scoped
81
+ ? "It is scoped to specific sites; make sure the listing explains why."
82
+ : broadHosts
83
+ ? "The condition is not scoped to specific sites and the extension has broad host access, so it weakens security on every page the user visits, whether or not the extension is in use."
84
+ : "The condition is not scoped to specific sites, but the extension's host access is narrow, which limits where it applies.";
85
+ const line = src.baseLine ?? (rule.id !== undefined ? findIdLine(src.text, rule.id) : undefined) ?? findLine(src.text, hits[0].header);
86
+ out.push({
87
+ ruleId: "SEC001",
88
+ severity,
89
+ confidence: "high",
90
+ title: "declarativeNetRequest rule strips security headers",
91
+ message: `DNR rule${id} uses modifyHeaders to ${what} on ${describeCondition(rule.condition)}. ${reach}${src.note ?? ""} Reviewers treat removing a site's security headers as harmful/unexpected behavior.`,
92
+ file: src.file,
93
+ line,
94
+ fixHint: "Scope the rule to the exact domains that need it (condition.requestDomains) and, if possible, only enable it while the feature is in use (updateEnabledRulesets / session rules). Explain the header change in the listing and the submission notes.",
95
+ });
96
+ }
97
+ return out;
98
+ }
99
+ function findIdLine(text, id) {
100
+ const re = new RegExp(`"id"\\s*:\\s*${String(id).replace(/[^\w]/g, "")}\\b`);
101
+ const lines = text.split(/\r?\n/);
102
+ for (let i = 0; i < lines.length; i++)
103
+ if (re.test(lines[i]))
104
+ return i + 1;
105
+ return undefined;
106
+ }
107
+ /** Convert a fully static AST literal (object/array/string/number/bool/null) to a value; undefined if not static. */
108
+ const NOT_STATIC = Symbol("not-static");
109
+ function staticValue(node) {
110
+ switch (node?.type) {
111
+ case "StringLiteral": return node.value;
112
+ case "NumericLiteral": return node.value;
113
+ case "BooleanLiteral": return node.value;
114
+ case "NullLiteral": return null;
115
+ case "TemplateLiteral":
116
+ return node.expressions?.length === 0 ? node.quasis?.[0]?.value?.cooked : NOT_STATIC;
117
+ case "ArrayExpression": {
118
+ const out = [];
119
+ for (const el of node.elements ?? []) {
120
+ const v = staticValue(el);
121
+ out.push(v === NOT_STATIC ? undefined : v); // keep other entries judgeable
122
+ }
123
+ return out;
124
+ }
125
+ case "ObjectExpression": {
126
+ const out = {};
127
+ for (const p of node.properties ?? []) {
128
+ if (p.type !== "ObjectProperty")
129
+ continue;
130
+ const key = p.computed ? staticValue(p.key) : p.key?.type === "Identifier" ? p.key.name : staticValue(p.key);
131
+ if (typeof key !== "string" && typeof key !== "number")
132
+ continue;
133
+ const v = staticValue(p.value);
134
+ if (v !== NOT_STATIC)
135
+ out[String(key)] = v;
136
+ }
137
+ return out;
138
+ }
139
+ default: return NOT_STATIC;
140
+ }
141
+ }
142
+ const DYNAMIC_METHODS = new Set(["updateDynamicRules", "updateSessionRules"]);
143
+ export function sec001(model) {
144
+ const broadHosts = hasBroadHostAccess(model);
145
+ const findings = [];
146
+ for (const rs of model.dnrRulesets) {
147
+ findings.push(...judge(model, {
148
+ file: rs.relPath,
149
+ rules: rs.rules,
150
+ text: rs.content,
151
+ note: rs.enabled ? "" : ` (Ruleset "${rs.id ?? rs.relPath}" is disabled by default but can be enabled at runtime.)`,
152
+ }, broadHosts));
153
+ }
154
+ for (const script of model.scriptFiles) {
155
+ if (!script.ast)
156
+ continue;
157
+ walk(script.ast, (node) => {
158
+ if (node.type !== "CallExpression" && node.type !== "OptionalCallExpression")
159
+ return;
160
+ const c = node.callee;
161
+ if ((c?.type !== "MemberExpression" && c?.type !== "OptionalMemberExpression") || c.computed)
162
+ return;
163
+ if (c.property?.type !== "Identifier" || !DYNAMIC_METHODS.has(c.property.name))
164
+ return;
165
+ const opts = staticValue(node.arguments?.[0]);
166
+ if (!opts || typeof opts !== "object")
167
+ return;
168
+ findings.push(...judge(model, {
169
+ file: script.relPath,
170
+ rules: opts.addRules,
171
+ text: script.content,
172
+ baseLine: node.loc?.start.line,
173
+ note: ` (Added at runtime via ${c.property.name}().)`,
174
+ }, broadHosts));
175
+ });
176
+ }
177
+ return findings;
178
+ }
179
+ export const securityRules = [sec001];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tabsmith-lint",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Pre-submission compliance linter for Manifest V3 Chrome extensions: flags likely Chrome Web Store rejection risks (unused/excessive permissions, MV3 violations, broken packaging) before you submit.",
5
5
  "type": "module",
6
6
  "bin": {