tabsmith-lint 0.2.0 → 0.4.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,9 @@ 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
+ | Harmful / unexpected behavior | DNR rules that strip sites' security headers | SEC001 |
29
30
 
30
31
  ```bash
31
32
  npx tabsmith-lint ./my-extension
@@ -82,7 +83,32 @@ exists, leave the severity at `fix`.
82
83
 
83
84
  ## Status
84
85
 
85
- Chrome-only, directory input, 12 rules (PERM001-005, MV3001-004, FUNC001-002).
86
+ Chrome-only, directory input, 13 rules (PERM001-005, MV3001-005, FUNC001-002, SEC001).
87
+
88
+ MV3001 (remotely hosted code, `reject`) covers HTML `<script src="https://…">`, remote
89
+ `import`/`import()`, remote `importScripts()`, a remote `src` set on a
90
+ `document.createElement("script")` element (`.src =`, `setAttribute("src", …)`,
91
+ `Object.assign(…, { src })`), and remote entries in
92
+ `chrome.scripting.executeScript({ files })` / `registerContentScripts([{ js }])` /
93
+ `updateContentScripts`. Fetching remote JSON/data with `fetch`/XHR is not
94
+ remotely hosted code and is never flagged; neither are `img`/`iframe` sources or
95
+ computed URLs.
96
+
97
+ MV3005 (latent remote-code loader) covers what MV3001 deliberately leaves out: bundled
98
+ code that *could* load a remote script. A `<script>` element (or `importScripts`) given
99
+ a computed `src` is `fix` when the URL is built on a remote prefix
100
+ (`"https://cdn/" + v`) or the same file also contains a remote `.js`/`.mjs` URL literal;
101
+ the finding names the URL and, when a banner or `vendor/` path identifies it, the
102
+ bundled package. Other remote `.js` URL literals in shipped code are `info` (they never
103
+ change the verdict). Only `.js`/`.mjs` URLs count, so remote JSON/data endpoints are
104
+ never flagged.
105
+
106
+ SEC001 (DNR security-header stripping) reads static `declarative_net_request` rulesets
107
+ and literal `updateDynamicRules`/`updateSessionRules` rules, and flags `modifyHeaders`
108
+ that `remove`/`set` `Content-Security-Policy`(-Report-Only), `X-Frame-Options`,
109
+ `Cross-Origin-Opener/Embedder/Resource-Policy` or `Strict-Transport-Security`. It is
110
+ `fix` when the condition isn't scoped to specific domains and the extension has broad
111
+ host access, otherwise `info`.
86
112
 
87
113
  Firefox/Edge, ZIP/CRX input, SARIF, and a GitHub Action are on the roadmap.
88
114
 
package/dist/cli.js CHANGED
@@ -23,15 +23,17 @@ function helpText() {
23
23
  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
- - Manifest V3 violations: remotely hosted code (script tags, import, importScripts),
27
- string execution, forbidden extension-page CSP, Manifest V2
26
+ - Manifest V3 violations: remotely hosted code (script tags, injected <script> src,
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, ...)
28
30
  - broken packaging: missing or wrong-case file references
29
31
 
30
32
  ${USAGE}
31
33
 
32
34
  Options:
33
35
  --format human|json output format (default: human)
34
- --browser chrome target browser (only chrome in v0.1)
36
+ --browser chrome target browser (only chrome is supported for now)
35
37
  --min-severity reject|fix|info minimum severity to report (default: info)
36
38
  -v, --version print version
37
39
  -h, --help show this help
@@ -66,7 +68,7 @@ export function run(argv) {
66
68
  if (!dir)
67
69
  return { exitCode: 3, stderr: `No extension directory provided.\n${USAGE}` };
68
70
  if (browser !== "chrome")
69
- return { exitCode: 3, stderr: `Only --browser chrome is supported in v0.1 (got "${browser}").` };
71
+ return { exitCode: 3, stderr: `Only --browser chrome is currently supported (got "${browser}").` };
70
72
  if (!["human", "json"].includes(format))
71
73
  return { exitCode: 3, stderr: `Invalid --format "${format}" (expected human|json).` };
72
74
  if (!["reject", "fix", "info"].includes(minSeverity))
@@ -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,8 @@ 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
+ export const allRules = [...permissionRules, ...mv3Rules, ...fileRules, ...securityRules];
6
7
  /** Run every rule and return all findings, ordered reject → fix → info. */
7
8
  export function runRules(model) {
8
9
  const findings = allRules.flatMap((rule) => rule(model));
package/dist/rules/mv3.js CHANGED
@@ -10,7 +10,9 @@ import { findLine, findLineByIndex } from "../engine/source-lines.js";
10
10
  // (MV3001 remote code and MV3003 manifest_version 2 stay `reject` — deterministic.)
11
11
  export const MV3002_SEVERITY = "fix";
12
12
  const REMOTE_SCRIPT_RE = /<script[^>]*\bsrc\s*=\s*["']((?:https?:)?\/\/[^"']+)["']/gi;
13
- /** MV3001 — remotely hosted code (HTML remote <script src>, remote import/import()). */
13
+ /** MV3001 — remotely hosted code (HTML remote <script src>, remote import/import(),
14
+ * importScripts, remote src on a JS-created <script> element, and remote entries
15
+ * in chrome.scripting.executeScript({files}) / registerContentScripts({js})). */
14
16
  function mv3001(model) {
15
17
  const findings = [];
16
18
  for (const html of model.htmlFiles) {
@@ -53,9 +55,258 @@ function mv3001(model) {
53
55
  }
54
56
  }
55
57
  });
58
+ findings.push(...injectedRemoteScripts(script.relPath, script.ast));
59
+ findings.push(...remoteScriptingFiles(script.relPath, script.ast));
56
60
  }
57
61
  return findings;
58
62
  }
63
+ // --- Injected <script> elements -------------------------------------------
64
+ // `const s = document.createElement("script"); s.src = "https://…"` (or
65
+ // `s.setAttribute("src", "https://…")`, or `Object.assign(s, {src: "https://…"})`)
66
+ // injects remotely hosted code exactly like an HTML <script src>. Precision first:
67
+ // - only elements created via `document.createElement("script")` (or
68
+ // `<x>.document` / `<x>.ownerDocument`) count — img/iframe/link/etc. never do;
69
+ // - a variable is tracked only if EVERY binding of that name in the file is such
70
+ // a createElement call (no parameter, other initializer or reassignment with
71
+ // the same name), so reused/minified names are skipped, never guessed;
72
+ // - only literal http(s):// or protocol-relative URLs are judged (computed URLs,
73
+ // local paths and chrome.runtime.getURL(...) are left alone);
74
+ // - fetch/XHR of remote JSON or data is not code execution and is never flagged.
75
+ function isScriptCreate(node) {
76
+ if (node?.type !== "CallExpression")
77
+ return false;
78
+ const callee = node.callee;
79
+ if (callee?.type !== "MemberExpression" || callee.computed)
80
+ return false;
81
+ if (callee.property?.type !== "Identifier" || callee.property.name !== "createElement")
82
+ return false;
83
+ const obj = callee.object;
84
+ const isDoc = (obj?.type === "Identifier" && obj.name === "document") ||
85
+ (obj?.type === "MemberExpression" &&
86
+ !obj.computed &&
87
+ obj.property?.type === "Identifier" &&
88
+ (obj.property.name === "document" || obj.property.name === "ownerDocument"));
89
+ if (!isDoc)
90
+ return false;
91
+ const tag = staticString(node.arguments?.[0]);
92
+ return typeof tag === "string" && tag.toLowerCase() === "script";
93
+ }
94
+ /** Identifiers bound by a declaration/parameter pattern. */
95
+ function patternNames(pattern, out = []) {
96
+ if (!pattern)
97
+ return out;
98
+ switch (pattern.type) {
99
+ case "Identifier":
100
+ out.push(pattern.name);
101
+ break;
102
+ case "ObjectPattern":
103
+ for (const p of pattern.properties ?? [])
104
+ patternNames(p.type === "RestElement" ? p.argument : p.value, out);
105
+ break;
106
+ case "ArrayPattern":
107
+ for (const e of pattern.elements ?? [])
108
+ patternNames(e, out);
109
+ break;
110
+ case "AssignmentPattern":
111
+ patternNames(pattern.left, out);
112
+ break;
113
+ case "RestElement":
114
+ patternNames(pattern.argument, out);
115
+ break;
116
+ case "TSParameterProperty":
117
+ patternNames(pattern.parameter, out);
118
+ break;
119
+ }
120
+ return out;
121
+ }
122
+ /** Names bound ONLY to document.createElement("script") anywhere in the file. */
123
+ function scriptElementNames(ast) {
124
+ const script = new Set();
125
+ const other = new Set();
126
+ walk(ast, (node) => {
127
+ if (node.type === "VariableDeclarator") {
128
+ if (node.id?.type === "Identifier" && isScriptCreate(node.init))
129
+ script.add(node.id.name);
130
+ else if (node.init)
131
+ patternNames(node.id).forEach((n) => other.add(n));
132
+ }
133
+ else if (node.type === "AssignmentExpression" && node.left?.type === "Identifier") {
134
+ if (node.operator === "=" && isScriptCreate(node.right))
135
+ script.add(node.left.name);
136
+ else
137
+ other.add(node.left.name);
138
+ }
139
+ else if (node.type === "AssignmentExpression" && node.left?.type !== "MemberExpression") {
140
+ patternNames(node.left).forEach((n) => other.add(n)); // destructuring assignment
141
+ }
142
+ else if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" ||
143
+ node.type === "ArrowFunctionExpression" || node.type === "ObjectMethod" || node.type === "ClassMethod") {
144
+ if (node.id?.type === "Identifier")
145
+ other.add(node.id.name);
146
+ for (const p of node.params ?? [])
147
+ patternNames(p).forEach((n) => other.add(n));
148
+ }
149
+ else if (node.type === "ClassDeclaration" && node.id?.type === "Identifier") {
150
+ other.add(node.id.name);
151
+ }
152
+ else if (node.type === "CatchClause") {
153
+ patternNames(node.param).forEach((n) => other.add(n));
154
+ }
155
+ else if (node.type === "ForInStatement" || node.type === "ForOfStatement") {
156
+ const left = node.left?.type === "VariableDeclaration" ? node.left.declarations?.[0]?.id : node.left;
157
+ patternNames(left).forEach((n) => other.add(n));
158
+ }
159
+ else if (node.type === "ImportSpecifier" || node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier") {
160
+ if (node.local?.type === "Identifier")
161
+ other.add(node.local.name);
162
+ }
163
+ else if (node.type === "UpdateExpression" && node.argument?.type === "Identifier") {
164
+ other.add(node.argument.name);
165
+ }
166
+ });
167
+ for (const n of other)
168
+ script.delete(n);
169
+ return script;
170
+ }
171
+ /** Every place a `document.createElement("script")` element gets its `src` set,
172
+ * literal or not: `.src =`, `["src"] =`, `setAttribute("src", …)`,
173
+ * `Object.assign(el, { src })`. Shared by MV3001 (literal remote URL) and
174
+ * MV3005 (computed URL = latent loader). */
175
+ function scriptSrcSets(ast) {
176
+ const names = scriptElementNames(ast);
177
+ const isScriptEl = (node) => isScriptCreate(node) || (node?.type === "Identifier" && names.has(node.name));
178
+ const out = [];
179
+ walk(ast, (node) => {
180
+ // <el>.src = … / <el>["src"] = …
181
+ if (node.type === "AssignmentExpression" && node.operator === "=" && node.left?.type === "MemberExpression") {
182
+ const left = node.left;
183
+ const prop = left.computed ? staticString(left.property) : left.property?.type === "Identifier" ? left.property.name : null;
184
+ if (prop === "src" && isScriptEl(left.object))
185
+ out.push({ node, value: node.right, how: ".src assignment" });
186
+ }
187
+ if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed) {
188
+ const method = node.callee.property?.type === "Identifier" ? node.callee.property.name : null;
189
+ // <el>.setAttribute("src", …)
190
+ if (method === "setAttribute" && isScriptEl(node.callee.object)) {
191
+ const attr = staticString(node.arguments?.[0]);
192
+ if (attr?.toLowerCase() === "src" && node.arguments?.[1]) {
193
+ out.push({ node, value: node.arguments[1], how: 'setAttribute("src")' });
194
+ }
195
+ }
196
+ // Object.assign(<el>, { src: … })
197
+ if (method === "assign" &&
198
+ node.callee.object?.type === "Identifier" &&
199
+ node.callee.object.name === "Object" &&
200
+ isScriptEl(node.arguments?.[0])) {
201
+ for (const src of node.arguments.slice(1)) {
202
+ if (src?.type !== "ObjectExpression")
203
+ continue;
204
+ for (const p of src.properties ?? []) {
205
+ if (p.type !== "ObjectProperty")
206
+ continue;
207
+ const key = p.computed ? staticString(p.key) : p.key?.type === "Identifier" ? p.key.name : staticString(p.key);
208
+ if (key === "src")
209
+ out.push({ node, value: p.value, how: "Object.assign({ src })" });
210
+ }
211
+ }
212
+ }
213
+ }
214
+ });
215
+ return out;
216
+ }
217
+ function injectedRemoteScripts(file, ast) {
218
+ const findings = [];
219
+ for (const { node, value, how } of scriptSrcSets(ast)) {
220
+ const url = staticString(value);
221
+ if (!isRemote(url))
222
+ continue;
223
+ findings.push({
224
+ ruleId: "MV3001",
225
+ severity: "reject",
226
+ confidence: "high",
227
+ title: "Remotely hosted code injected via a <script> element",
228
+ message: `${how} points a dynamically created <script> element at "${url}", which loads and runs remote code. Manifest V3 forbids remotely hosted code.`,
229
+ file,
230
+ line: node.loc?.start.line,
231
+ column: node.loc?.start.column,
232
+ chromeViolationId: "Blue Argon",
233
+ 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.",
234
+ });
235
+ }
236
+ return findings;
237
+ }
238
+ // --- chrome.scripting with remote files ------------------------------------
239
+ // `chrome.scripting.executeScript({ files: ["https://…"] })` and
240
+ // `chrome.scripting.registerContentScripts([{ js: ["https://…"] }])` (also
241
+ // updateContentScripts, and the browser.* namespace) name remote code as the
242
+ // thing to inject. Only literal http(s):// or protocol-relative entries are
243
+ // judged; local paths and computed entries are left alone. CSS entries are not
244
+ // code and are not judged.
245
+ const SCRIPTING_METHODS = new Set(["executeScript", "registerContentScripts", "updateContentScripts"]);
246
+ function scriptingMethod(callee) {
247
+ if (callee?.type !== "MemberExpression" && callee?.type !== "OptionalMemberExpression")
248
+ return null;
249
+ if (callee.computed || callee.property?.type !== "Identifier" || !SCRIPTING_METHODS.has(callee.property.name))
250
+ return null;
251
+ const obj = callee.object;
252
+ if ((obj?.type !== "MemberExpression" && obj?.type !== "OptionalMemberExpression") || obj.computed)
253
+ return null;
254
+ if (obj.property?.type !== "Identifier" || obj.property.name !== "scripting")
255
+ return null;
256
+ return callee.property.name;
257
+ }
258
+ function objectProp(obj, name) {
259
+ if (obj?.type !== "ObjectExpression")
260
+ return undefined;
261
+ for (const p of obj.properties ?? []) {
262
+ if (p.type !== "ObjectProperty")
263
+ continue;
264
+ const key = p.computed ? staticString(p.key) : p.key?.type === "Identifier" ? p.key.name : staticString(p.key);
265
+ if (key === name)
266
+ return p.value;
267
+ }
268
+ return undefined;
269
+ }
270
+ function remoteScriptingFiles(file, ast) {
271
+ const findings = [];
272
+ walk(ast, (node) => {
273
+ if (node.type !== "CallExpression" && node.type !== "OptionalCallExpression")
274
+ return;
275
+ const method = scriptingMethod(node.callee);
276
+ if (!method)
277
+ return;
278
+ const arg = node.arguments?.[0];
279
+ const lists = [];
280
+ if (method === "executeScript")
281
+ lists.push(objectProp(arg, "files"));
282
+ else if (arg?.type === "ArrayExpression")
283
+ for (const el of arg.elements ?? [])
284
+ lists.push(objectProp(el, "js"));
285
+ for (const list of lists) {
286
+ if (list?.type !== "ArrayExpression")
287
+ continue;
288
+ for (const el of list.elements ?? []) {
289
+ const url = staticString(el);
290
+ if (!isRemote(url))
291
+ continue;
292
+ const key = method === "executeScript" ? "files" : "js";
293
+ findings.push({
294
+ ruleId: "MV3001",
295
+ severity: "reject",
296
+ confidence: "high",
297
+ title: "Remotely hosted code passed to chrome.scripting",
298
+ 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).`,
299
+ file,
300
+ line: el.loc?.start.line ?? node.loc?.start.line,
301
+ column: el.loc?.start.column,
302
+ chromeViolationId: "Blue Argon",
303
+ fixHint: `Bundle the script in the extension package and list its packaged path in ${key} (e.g. "scripts/content.js").`,
304
+ });
305
+ }
306
+ }
307
+ });
308
+ return findings;
309
+ }
59
310
  function isRemote(v) {
60
311
  return typeof v === "string" && /^(https?:)?\/\//i.test(v);
61
312
  }
@@ -96,6 +347,142 @@ function remoteImport(file, node, url, via = "import") {
96
347
  : "Bundle the dependency inside the extension package instead of importing it remotely.",
97
348
  };
98
349
  }
350
+ // --- MV3005: latent remote-code loaders ------------------------------------
351
+ // Review judges what bundled code *could* do, not just what it does by default
352
+ // (e.g. a shared widget that can inject an rrweb recorder <script> it never
353
+ // uses still drew a Blue Argon rejection). MV3005 surfaces that tier without
354
+ // condemning it, so it ships at `fix` / `info`, never `reject`:
355
+ // (a) `fix`: a createElement("script") element (or importScripts) is given a
356
+ // COMPUTED src, and either the expression starts with a remote URL prefix
357
+ // (`"https://cdn/" + v`, `` `https://cdn/${v}.js` ``) or the same file also
358
+ // contains a remote `.js`/`.mjs` URL string literal;
359
+ // (b) `info`: remote `.js`/`.mjs` URL string literals in shipped JS that no
360
+ // MV3001/MV3005 finding already explains (one finding per file).
361
+ // Precision: only URLs whose path ends in .js/.mjs count, so remote JSON/data
362
+ // endpoints, images and pages are never flagged; chrome.runtime.getURL(...)
363
+ // sources are local; literal remote srcs are MV3001's job.
364
+ const REMOTE_JS_RE = /^(?:https?:)?\/\/[^\s"'`<>()]+\.m?js(?:[?#][^\s"'`<>]*)?$/i;
365
+ // Links to a source-code *page* (GitHub/GitLab/Bitbucket blob/tree views) are documentation, not scripts.
366
+ const SOURCE_VIEWER_RE = /^(?:https?:)?\/\/(?:www\.)?(?:github\.com|gitlab\.com|bitbucket\.org)\/[^?#]*\/(?:blob|tree|src)\//i;
367
+ function isRemoteJsUrl(v) {
368
+ return typeof v === "string" && v.length < 2048 && REMOTE_JS_RE.test(v) && !SOURCE_VIEWER_RE.test(v);
369
+ }
370
+ /** chrome|browser.runtime.getURL(...) / .extension.getURL(...) → a packaged file. */
371
+ function isGetUrlCall(node) {
372
+ if (node?.type !== "CallExpression")
373
+ return false;
374
+ const c = node.callee;
375
+ return (c?.type === "MemberExpression" && !c.computed &&
376
+ c.property?.type === "Identifier" && c.property.name === "getURL" &&
377
+ c.object?.type === "MemberExpression" && !c.object.computed &&
378
+ c.object.property?.type === "Identifier" &&
379
+ (c.object.property.name === "runtime" || c.object.property.name === "extension"));
380
+ }
381
+ /** Leading static text of a string-building expression ("a" + x, `a${x}`). */
382
+ function staticPrefix(node) {
383
+ if (node?.type === "StringLiteral")
384
+ return node.value;
385
+ if (node?.type === "TemplateLiteral")
386
+ return node.quasis?.[0]?.value?.cooked ?? null;
387
+ if (node?.type === "BinaryExpression" && node.operator === "+")
388
+ return staticPrefix(node.left);
389
+ return null;
390
+ }
391
+ const BANNER_RE = /^\s*(?:\/\*[!*]?|\/\/)\s*(?:@license\s+)?(@?[A-Za-z][\w./-]*)\s+v?(\d+\.\d+\.\d+[\w.-]*)/;
392
+ const VENDOR_DIR_RE = /(?:^|\/)(?:vendor|vendors|third[_-]?party|lib|libs)\/([^/]+?)(?:\.min)?\.m?js$/i;
393
+ /** Best-effort name of the bundled package a file comes from (banner or vendor path). */
394
+ export function probablePackage(relPath, content) {
395
+ const b = BANNER_RE.exec(content.slice(0, 1000));
396
+ if (b)
397
+ return `${b[1]}@${b[2]}`;
398
+ const v = VENDOR_DIR_RE.exec(relPath);
399
+ return v ? v[1] : null;
400
+ }
401
+ function remoteJsLiterals(ast) {
402
+ const out = [];
403
+ walk(ast, (node) => {
404
+ const v = node.type === "StringLiteral" || node.type === "TemplateLiteral" ? staticString(node) : null;
405
+ if (isRemoteJsUrl(v))
406
+ out.push({ url: v, line: node.loc?.start.line });
407
+ });
408
+ return out;
409
+ }
410
+ function mv3005(model) {
411
+ const findings = [];
412
+ const explained = new Set(); // file\0url already covered by MV3001
413
+ for (const f of mv3001(model)) {
414
+ if (!f.file)
415
+ continue;
416
+ for (const m of f.message.matchAll(/"([^"]+)"/g))
417
+ explained.add(`${f.file}\0${m[1]}`);
418
+ }
419
+ for (const script of model.scriptFiles) {
420
+ if (!script.ast)
421
+ continue;
422
+ const file = script.relPath;
423
+ const literals = remoteJsLiterals(script.ast).filter((l) => !explained.has(`${file}\0${l.url}`));
424
+ const urls = [...new Set(literals.map((l) => l.url))];
425
+ const pkg = probablePackage(file, script.content);
426
+ const from = pkg ? ` This file looks like bundled code from ${pkg}.` : "";
427
+ const list = (u) => u.slice(0, 3).map((x) => `"${x}"`).join(", ") + (u.length > 3 ? ` (+${u.length - 3} more)` : "");
428
+ const sinks = scriptSrcSets(script.ast).filter((s) => staticString(s.value) === null);
429
+ walk(script.ast, (node) => {
430
+ if (node.type === "CallExpression" && isImportScriptsCallee(node.callee)) {
431
+ for (const arg of node.arguments ?? []) {
432
+ if (staticString(arg) === null && arg.type !== "SpreadElement")
433
+ sinks.push({ node, value: arg, how: "importScripts()" });
434
+ }
435
+ }
436
+ });
437
+ // One `fix` finding per file (first loader), other loader lines listed, to keep bundles readable.
438
+ let latent = false;
439
+ const hits = [];
440
+ for (const { node, value, how } of sinks) {
441
+ if (isGetUrlCall(value))
442
+ continue;
443
+ const prefix = staticPrefix(value);
444
+ if (isRemote(prefix)) {
445
+ hits.push({ node, message: `${how} loads a script from a URL built at runtime on the remote prefix "${prefix}". Even if this path never runs, reviewers treat it as remotely hosted code.` });
446
+ }
447
+ else if (urls.length > 0) {
448
+ latent = true;
449
+ 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.` });
450
+ }
451
+ }
452
+ if (hits.length > 0) {
453
+ hits.sort((a, b) => (a.node.loc?.start.index ?? 0) - (b.node.loc?.start.index ?? 0));
454
+ const first = hits[0];
455
+ const more = [...new Set(hits.slice(1).map((h) => h.node.loc?.start.line).filter((l) => l !== undefined && l !== first.node.loc?.start.line))];
456
+ const also = more.length ? ` Other script loads in this file: line${more.length > 1 ? "s" : ""} ${more.slice(0, 10).join(", ")}${more.length > 10 ? ", …" : ""}.` : "";
457
+ findings.push({
458
+ ruleId: "MV3005",
459
+ severity: "fix",
460
+ confidence: "medium",
461
+ title: "Latent remote-code loader",
462
+ message: first.message + also + from,
463
+ file,
464
+ line: first.node.loc?.start.line,
465
+ column: first.node.loc?.start.column,
466
+ chromeViolationId: "Blue Argon",
467
+ 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.",
468
+ });
469
+ }
470
+ if (!latent && urls.length > 0) {
471
+ findings.push({
472
+ ruleId: "MV3005",
473
+ severity: "info",
474
+ confidence: "low",
475
+ title: "Remote script URL in shipped code",
476
+ message: `Shipped code contains the remote script URL ${list(urls)}. No loader was found for it, but reviewers search bundles for remote .js URLs; check that nothing can load it.${from}`,
477
+ file,
478
+ line: literals[0]?.line,
479
+ chromeViolationId: "Blue Argon",
480
+ fixHint: "Remove unused remote script URLs at build time, or explain them in the submission notes.",
481
+ });
482
+ }
483
+ }
484
+ return findings;
485
+ }
99
486
  const STRING_TIMERS = new Set(["setTimeout", "setInterval"]);
100
487
  /** MV3002 — string execution (eval, new Function, string-form timers). */
101
488
  function mv3002(model) {
@@ -224,4 +611,4 @@ function mv3004(model) {
224
611
  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).",
225
612
  }];
226
613
  }
227
- export const mv3Rules = [mv3001, mv3002, mv3003, mv3004];
614
+ export const mv3Rules = [mv3001, mv3002, mv3003, mv3004, mv3005];
@@ -166,7 +166,7 @@ function perm005(model) {
166
166
  message: `Broad host patterns requested: ${[...new Set(broad)].join(", ")}.`,
167
167
  file: "manifest.json",
168
168
  line: findLine(model.manifestRaw, broad[0]),
169
- fixHint: `Replace broad patterns with the narrowest required host patterns.`,
169
+ fixHint: `Replace broad patterns with the narrowest required host patterns. If broad access is only needed for some users or features, move it to "optional_host_permissions" and request it at runtime with chrome.permissions.request().`,
170
170
  }];
171
171
  }
172
172
  export const permissionRules = [perm001, perm002, perm003, perm004, perm005];
@@ -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,10 +1,10 @@
1
1
  {
2
2
  "name": "tabsmith-lint",
3
- "version": "0.2.0",
3
+ "version": "0.4.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": {
7
- "tabsmith-lint": "./dist/cli.js"
7
+ "tabsmith-lint": "dist/cli.js"
8
8
  },
9
9
  "files": [
10
10
  "dist"
@@ -56,6 +56,6 @@
56
56
  "devDependencies": {
57
57
  "@types/node": "^20.12.0",
58
58
  "typescript": "^5.4.0",
59
- "vitest": "^3.2.6"
59
+ "vitest": "^4.1.12"
60
60
  }
61
61
  }