tabsmith-lint 0.1.3 → 0.3.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
@@ -1,6 +1,16 @@
1
1
  # tabsmith-lint
2
2
 
3
- A pre-submission compliance linter for browser extensions. v0.1 analyzes an unpacked
3
+ <p>
4
+ <a href="https://www.npmjs.com/package/tabsmith-lint"><img alt="npm version" height="28" src="https://img.shields.io/npm/v/tabsmith-lint?logo=npm&color=cb3837"></a>
5
+ <a href="https://www.npmjs.com/package/tabsmith-lint"><img alt="npm downloads" height="28" src="https://img.shields.io/npm/dt/tabsmith-lint?logo=npm&color=cb3837"></a>
6
+ <a href="https://github.com/rsub122/tabsmith-lint/actions/workflows/ci.yml"><img alt="CI" height="28" src="https://img.shields.io/github/actions/workflow/status/rsub122/tabsmith-lint/ci.yml?branch=main&logo=github&label=CI"></a>
7
+ <a href="https://github.com/rsub122/tabsmith-lint/blob/main/package.json"><img alt="node" height="28" src="https://img.shields.io/node/v/tabsmith-lint?logo=node.js"></a>
8
+ <a href="LICENSE"><img alt="license" height="28" src="https://img.shields.io/npm/l/tabsmith-lint?color=blue"></a>
9
+ <a href="https://packagephobia.com/result?p=tabsmith-lint"><img alt="install size" height="28" src="https://packagephobia.com/badge?p=tabsmith-lint"></a>
10
+ <a href="https://github.com/rsub122/tabsmith-lint/stargazers"><img alt="GitHub stars" height="28" src="https://img.shields.io/github/stars/rsub122/tabsmith-lint?style=flat&logo=github"></a>
11
+ </p>
12
+
13
+ A pre-submission compliance linter for browser extensions. It analyzes an unpacked
4
14
  Manifest V3 Chrome extension directory and reports likely Chrome Web Store rejection
5
15
  risks **before** you submit — unused/excessive permissions, missing permissions, MV3
6
16
  violations, and broken file references — with a clear verdict and actionable fixes.
@@ -14,7 +24,7 @@ Chrome reviewers flag:
14
24
  | Violation ID | What it means | tabsmith rules |
15
25
  |---|---|---|
16
26
  | Purple Potassium | Excessive / unused permissions | PERM001, PERM003, PERM004, PERM005 |
17
- | Blue Argon | Remotely hosted code / string execution | MV3001, MV3002 |
27
+ | Blue Argon | Remotely hosted code / string execution / forbidden CSP | MV3001, MV3002, MV3004 |
18
28
  | Yellow Magnesium | Functionality / broken packaging | FUNC001, FUNC002 |
19
29
 
20
30
  ```bash
@@ -72,7 +82,14 @@ exists, leave the severity at `fix`.
72
82
 
73
83
  ## Status
74
84
 
75
- v0.1. Chrome-only, directory input, 10 rules (PERM001-005, MV3001-003, FUNC001-002).
85
+ Chrome-only, directory input, 11 rules (PERM001-005, MV3001-004, FUNC001-002).
86
+
87
+ MV3001 (remotely hosted code, `reject`) covers HTML `<script src="https://…">`, remote
88
+ `import`/`import()`, remote `importScripts()`, and a remote `src` set on a
89
+ `document.createElement("script")` element (`.src =`, `setAttribute("src", …)`,
90
+ `Object.assign(…, { src })`). Fetching remote JSON/data with `fetch`/XHR is not
91
+ remotely hosted code and is never flagged; neither are `img`/`iframe` sources or
92
+ computed URLs.
76
93
 
77
94
  Firefox/Edge, ZIP/CRX input, SARIF, and a GitHub Action are on the roadmap.
78
95
 
package/dist/cli.js CHANGED
@@ -23,14 +23,15 @@ 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, string execution, Manifest V2
26
+ - Manifest V3 violations: remotely hosted code (script tags, injected <script> src,
27
+ import, importScripts), string execution, forbidden extension-page CSP, Manifest V2
27
28
  - broken packaging: missing or wrong-case file references
28
29
 
29
30
  ${USAGE}
30
31
 
31
32
  Options:
32
33
  --format human|json output format (default: human)
33
- --browser chrome target browser (only chrome in v0.1)
34
+ --browser chrome target browser (only chrome is supported for now)
34
35
  --min-severity reject|fix|info minimum severity to report (default: info)
35
36
  -v, --version print version
36
37
  -h, --help show this help
@@ -65,7 +66,7 @@ export function run(argv) {
65
66
  if (!dir)
66
67
  return { exitCode: 3, stderr: `No extension directory provided.\n${USAGE}` };
67
68
  if (browser !== "chrome")
68
- return { exitCode: 3, stderr: `Only --browser chrome is supported in v0.1 (got "${browser}").` };
69
+ return { exitCode: 3, stderr: `Only --browser chrome is currently supported (got "${browser}").` };
69
70
  if (!["human", "json"].includes(format))
70
71
  return { exitCode: 3, stderr: `Invalid --format "${format}" (expected human|json).` };
71
72
  if (!["reject", "fix", "info"].includes(minSeverity))
package/dist/rules/mv3.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { walk } from "../parse/parse-script.js";
2
- import { findLineByIndex } from "../engine/source-lines.js";
2
+ import { findLine, findLineByIndex } from "../engine/source-lines.js";
3
3
  // MV3002 (string execution: eval/new Function/string timers) ships at `fix`, not
4
4
  // `reject`, in v0.1. The pattern is a real MV3 CSP concern, but static analysis
5
5
  // cannot tell whether the call is reachable or runs in a sandboxed context — and
@@ -10,7 +10,8 @@ import { 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, and remote src on a JS-created <script> element). */
14
15
  function mv3001(model) {
15
16
  const findings = [];
16
17
  for (const html of model.htmlFiles) {
@@ -42,24 +43,223 @@ function mv3001(model) {
42
43
  if (node.type === "CallExpression" && node.callee?.type === "Import" && isRemote(node.arguments?.[0]?.value)) {
43
44
  findings.push(remoteImport(script.relPath, node, node.arguments[0].value));
44
45
  }
46
+ // importScripts("https://...") — the classic service-worker remote loader.
47
+ // Only string-literal (or expression-free template) arguments are judged;
48
+ // computed URLs are left alone (no guessing).
49
+ if (node.type === "CallExpression" && isImportScriptsCallee(node.callee)) {
50
+ for (const arg of node.arguments ?? []) {
51
+ const url = staticString(arg);
52
+ if (isRemote(url))
53
+ findings.push(remoteImport(script.relPath, node, url, "importScripts"));
54
+ }
55
+ }
45
56
  });
57
+ findings.push(...injectedRemoteScripts(script.relPath, script.ast));
46
58
  }
47
59
  return findings;
48
60
  }
61
+ // --- Injected <script> elements -------------------------------------------
62
+ // `const s = document.createElement("script"); s.src = "https://…"` (or
63
+ // `s.setAttribute("src", "https://…")`, or `Object.assign(s, {src: "https://…"})`)
64
+ // injects remotely hosted code exactly like an HTML <script src>. Precision first:
65
+ // - only elements created via `document.createElement("script")` (or
66
+ // `<x>.document` / `<x>.ownerDocument`) count — img/iframe/link/etc. never do;
67
+ // - a variable is tracked only if EVERY binding of that name in the file is such
68
+ // a createElement call (no parameter, other initializer or reassignment with
69
+ // the same name), so reused/minified names are skipped, never guessed;
70
+ // - only literal http(s):// or protocol-relative URLs are judged (computed URLs,
71
+ // local paths and chrome.runtime.getURL(...) are left alone);
72
+ // - fetch/XHR of remote JSON or data is not code execution and is never flagged.
73
+ function isScriptCreate(node) {
74
+ if (node?.type !== "CallExpression")
75
+ return false;
76
+ const callee = node.callee;
77
+ if (callee?.type !== "MemberExpression" || callee.computed)
78
+ return false;
79
+ if (callee.property?.type !== "Identifier" || callee.property.name !== "createElement")
80
+ return false;
81
+ const obj = callee.object;
82
+ const isDoc = (obj?.type === "Identifier" && obj.name === "document") ||
83
+ (obj?.type === "MemberExpression" &&
84
+ !obj.computed &&
85
+ obj.property?.type === "Identifier" &&
86
+ (obj.property.name === "document" || obj.property.name === "ownerDocument"));
87
+ if (!isDoc)
88
+ return false;
89
+ const tag = staticString(node.arguments?.[0]);
90
+ return typeof tag === "string" && tag.toLowerCase() === "script";
91
+ }
92
+ /** Identifiers bound by a declaration/parameter pattern. */
93
+ function patternNames(pattern, out = []) {
94
+ if (!pattern)
95
+ return out;
96
+ switch (pattern.type) {
97
+ case "Identifier":
98
+ out.push(pattern.name);
99
+ break;
100
+ case "ObjectPattern":
101
+ for (const p of pattern.properties ?? [])
102
+ patternNames(p.type === "RestElement" ? p.argument : p.value, out);
103
+ break;
104
+ case "ArrayPattern":
105
+ for (const e of pattern.elements ?? [])
106
+ patternNames(e, out);
107
+ break;
108
+ case "AssignmentPattern":
109
+ patternNames(pattern.left, out);
110
+ break;
111
+ case "RestElement":
112
+ patternNames(pattern.argument, out);
113
+ break;
114
+ case "TSParameterProperty":
115
+ patternNames(pattern.parameter, out);
116
+ break;
117
+ }
118
+ return out;
119
+ }
120
+ /** Names bound ONLY to document.createElement("script") anywhere in the file. */
121
+ function scriptElementNames(ast) {
122
+ const script = new Set();
123
+ const other = new Set();
124
+ walk(ast, (node) => {
125
+ if (node.type === "VariableDeclarator") {
126
+ if (node.id?.type === "Identifier" && isScriptCreate(node.init))
127
+ script.add(node.id.name);
128
+ else if (node.init)
129
+ patternNames(node.id).forEach((n) => other.add(n));
130
+ }
131
+ else if (node.type === "AssignmentExpression" && node.left?.type === "Identifier") {
132
+ if (node.operator === "=" && isScriptCreate(node.right))
133
+ script.add(node.left.name);
134
+ else
135
+ other.add(node.left.name);
136
+ }
137
+ else if (node.type === "AssignmentExpression" && node.left?.type !== "MemberExpression") {
138
+ patternNames(node.left).forEach((n) => other.add(n)); // destructuring assignment
139
+ }
140
+ else if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" ||
141
+ node.type === "ArrowFunctionExpression" || node.type === "ObjectMethod" || node.type === "ClassMethod") {
142
+ if (node.id?.type === "Identifier")
143
+ other.add(node.id.name);
144
+ for (const p of node.params ?? [])
145
+ patternNames(p).forEach((n) => other.add(n));
146
+ }
147
+ else if (node.type === "ClassDeclaration" && node.id?.type === "Identifier") {
148
+ other.add(node.id.name);
149
+ }
150
+ else if (node.type === "CatchClause") {
151
+ patternNames(node.param).forEach((n) => other.add(n));
152
+ }
153
+ else if (node.type === "ForInStatement" || node.type === "ForOfStatement") {
154
+ const left = node.left?.type === "VariableDeclaration" ? node.left.declarations?.[0]?.id : node.left;
155
+ patternNames(left).forEach((n) => other.add(n));
156
+ }
157
+ else if (node.type === "ImportSpecifier" || node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier") {
158
+ if (node.local?.type === "Identifier")
159
+ other.add(node.local.name);
160
+ }
161
+ else if (node.type === "UpdateExpression" && node.argument?.type === "Identifier") {
162
+ other.add(node.argument.name);
163
+ }
164
+ });
165
+ for (const n of other)
166
+ script.delete(n);
167
+ return script;
168
+ }
169
+ function injectedRemoteScripts(file, ast) {
170
+ const names = scriptElementNames(ast);
171
+ 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
+ });
185
+ walk(ast, (node) => {
186
+ // <el>.src = "https://…" / <el>["src"] = "https://…"
187
+ if (node.type === "AssignmentExpression" && node.operator === "=" && node.left?.type === "MemberExpression") {
188
+ const left = node.left;
189
+ 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");
193
+ }
194
+ if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed) {
195
+ const method = node.callee.property?.type === "Identifier" ? node.callee.property.name : null;
196
+ // <el>.setAttribute("src", "https://…")
197
+ if (method === "setAttribute" && isScriptEl(node.callee.object)) {
198
+ 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")');
202
+ }
203
+ // Object.assign(<el>, { src: "https://…" })
204
+ if (method === "assign" &&
205
+ node.callee.object?.type === "Identifier" &&
206
+ node.callee.object.name === "Object" &&
207
+ isScriptEl(node.arguments?.[0])) {
208
+ for (const src of node.arguments.slice(1)) {
209
+ if (src?.type !== "ObjectExpression")
210
+ continue;
211
+ for (const p of src.properties ?? []) {
212
+ if (p.type !== "ObjectProperty")
213
+ continue;
214
+ 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 })");
218
+ }
219
+ }
220
+ }
221
+ }
222
+ });
223
+ return findings;
224
+ }
49
225
  function isRemote(v) {
50
226
  return typeof v === "string" && /^(https?:)?\/\//i.test(v);
51
227
  }
52
- function remoteImport(file, node, url) {
228
+ /** importScripts, self.importScripts, globalThis.importScripts. */
229
+ function isImportScriptsCallee(callee) {
230
+ if (callee?.type === "Identifier")
231
+ return callee.name === "importScripts";
232
+ return (callee?.type === "MemberExpression" &&
233
+ !callee.computed &&
234
+ callee.property?.type === "Identifier" &&
235
+ callee.property.name === "importScripts" &&
236
+ callee.object?.type === "Identifier" &&
237
+ (callee.object.name === "self" || callee.object.name === "globalThis"));
238
+ }
239
+ /** The value of a string literal or an expression-free template literal, else null. */
240
+ function staticString(arg) {
241
+ if (arg?.type === "StringLiteral")
242
+ return arg.value;
243
+ if (arg?.type === "TemplateLiteral" && arg.expressions?.length === 0 && arg.quasis?.length === 1) {
244
+ return arg.quasis[0].value?.cooked ?? null;
245
+ }
246
+ return null;
247
+ }
248
+ function remoteImport(file, node, url, via = "import") {
53
249
  return {
54
250
  ruleId: "MV3001",
55
251
  severity: "reject",
56
252
  confidence: "high",
57
253
  title: "Remotely hosted code referenced",
58
- message: `import of "${url}" loads code from a remote URL, which Manifest V3 forbids.`,
254
+ message: via === "importScripts"
255
+ ? `importScripts("${url}") loads code from a remote URL, which Manifest V3 forbids.`
256
+ : `import of "${url}" loads code from a remote URL, which Manifest V3 forbids.`,
59
257
  file,
60
258
  line: node.loc?.start.line,
61
259
  chromeViolationId: "Blue Argon",
62
- fixHint: "Bundle the dependency inside the extension package instead of importing it remotely.",
260
+ fixHint: via === "importScripts"
261
+ ? "Bundle the script inside the extension package and importScripts() the local copy."
262
+ : "Bundle the dependency inside the extension package instead of importing it remotely.",
63
263
  };
64
264
  }
65
265
  const STRING_TIMERS = new Set(["setTimeout", "setInterval"]);
@@ -118,4 +318,76 @@ function mv3003(model) {
118
318
  fixHint: "Migrate the extension to Manifest V3.",
119
319
  }];
120
320
  }
121
- export const mv3Rules = [mv3001, mv3002, mv3003];
321
+ // MV3004 — extension-page CSP that Chrome's Manifest V3 forbids. For
322
+ // `content_security_policy.extension_pages`, script-src / object-src / worker-src
323
+ // may only contain 'self', 'none', 'wasm-unsafe-eval', 'inline-speculation-rules'
324
+ // and localhost sources; anything laxer (unsafe-eval, unsafe-inline, remote
325
+ // origins) makes Chrome refuse to load the extension. The `sandbox` policy is
326
+ // exempt and is never inspected. Nonces/hashes are not judged (conservative).
327
+ const CSP_RESTRICTED = new Set(["script-src", "object-src", "worker-src"]);
328
+ const CSP_ALLOWED_KEYWORDS = new Set(["'self'", "'none'", "'wasm-unsafe-eval'", "'inline-speculation-rules'"]);
329
+ const CSP_LOCALHOST_RE = /^(https?:\/\/)?(localhost|127\.0\.0\.1)(:(\d+|\*))?(\/.*)?$/i;
330
+ function cspViolations(policy) {
331
+ const bad = [];
332
+ for (const directive of policy.split(";")) {
333
+ const [rawName, ...sources] = directive.trim().split(/\s+/);
334
+ const name = rawName?.toLowerCase();
335
+ if (!name || !CSP_RESTRICTED.has(name))
336
+ continue;
337
+ for (const src of sources) {
338
+ const lower = src.toLowerCase();
339
+ if (CSP_ALLOWED_KEYWORDS.has(lower))
340
+ continue;
341
+ if (lower.startsWith("'nonce-") || lower.startsWith("'sha"))
342
+ continue; // not judged
343
+ if (lower === "'unsafe-eval'" || lower === "'unsafe-inline'") {
344
+ bad.push(`${name} ${src}`);
345
+ }
346
+ else if (lower.startsWith("'")) {
347
+ continue; // unknown keyword — don't guess
348
+ }
349
+ else if (!CSP_LOCALHOST_RE.test(src)) {
350
+ bad.push(`${name} ${src}`); // remote origin, wildcard, or scheme source
351
+ }
352
+ }
353
+ }
354
+ return bad;
355
+ }
356
+ function mv3004(model) {
357
+ if (model.manifest.manifest_version !== 3)
358
+ return [];
359
+ const csp = model.manifest.content_security_policy;
360
+ if (csp === undefined || csp === null)
361
+ return [];
362
+ const line = findLine(model.manifestRaw, "content_security_policy");
363
+ if (typeof csp === "string") {
364
+ return [{
365
+ ruleId: "MV3004",
366
+ severity: "reject",
367
+ confidence: "high",
368
+ title: "content_security_policy must be an object in Manifest V3",
369
+ message: 'content_security_policy is a string (the Manifest V2 form). Manifest V3 requires an object such as {"extension_pages": "script-src \'self\'; object-src \'self\'"}.',
370
+ file: "manifest.json",
371
+ line,
372
+ fixHint: 'Use {"extension_pages": "..."} (and "sandbox" if needed) instead of a single string.',
373
+ }];
374
+ }
375
+ const pages = csp && typeof csp === "object" ? csp.extension_pages : undefined;
376
+ if (typeof pages !== "string")
377
+ return [];
378
+ const bad = cspViolations(pages);
379
+ if (bad.length === 0)
380
+ return [];
381
+ return [{
382
+ ruleId: "MV3004",
383
+ severity: "reject",
384
+ confidence: "high",
385
+ title: "extension_pages CSP is looser than Manifest V3 allows",
386
+ message: `content_security_policy.extension_pages contains ${bad.map((b) => `"${b}"`).join(", ")}. Manifest V3 only allows 'self', 'none', 'wasm-unsafe-eval' and localhost sources for script-src, object-src and worker-src, so Chrome will not load or accept this extension.`,
387
+ file: "manifest.json",
388
+ line: findLine(model.manifestRaw, "extension_pages") ?? line,
389
+ chromeViolationId: "Blue Argon",
390
+ 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
+ }];
392
+ }
393
+ export const mv3Rules = [mv3001, mv3002, mv3003, mv3004];
@@ -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];
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "tabsmith-lint",
3
- "version": "0.1.3",
3
+ "version": "0.3.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
  }