tabsmith-lint 0.4.0 → 0.6.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
@@ -11,8 +11,8 @@
11
11
  </p>
12
12
 
13
13
  A pre-submission compliance linter for browser extensions. It analyzes an unpacked
14
- Manifest V3 Chrome extension directory and reports likely Chrome Web Store rejection
15
- risks **before** you submit — unused/excessive permissions, missing permissions, MV3
14
+ Manifest V3 Chrome extension (an unpacked directory, or the `.zip`/`.crx` you upload)
15
+ and reports likely Chrome Web Store rejection risks **before** you submit — unused/excessive permissions, missing permissions, MV3
16
16
  violations, and broken file references — with a clear verdict and actionable fixes.
17
17
 
18
18
  **Catch the "Purple Potassium" permission rejection before you submit.** The most
@@ -26,12 +26,15 @@ Chrome reviewers flag:
26
26
  | Purple Potassium | Excessive / unused permissions | PERM001, PERM003, PERM004, PERM005 |
27
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 |
29
30
  | Harmful / unexpected behavior | DNR rules that strip sites' security headers | SEC001 |
31
+ | Upload / package hygiene | Secrets, `.git`, `node_modules` etc. in the zip; 2 GB limit; leftover `"key"` | PKG001, PKG003, PKG002 |
30
32
 
31
33
  ```bash
32
34
  npx tabsmith-lint ./my-extension
33
35
  npx tabsmith-lint ./my-extension --format json
34
36
  npx tabsmith-lint ./my-extension --min-severity reject
37
+ npx tabsmith-lint ./my-extension.zip # lint exactly what you upload (.zip or .crx)
35
38
  ```
36
39
 
37
40
  Exit codes: `0` pass · `1` needs fixes · `2` high rejection risk · `3` tool error.
@@ -83,7 +86,8 @@ exists, leave the severity at `fix`.
83
86
 
84
87
  ## Status
85
88
 
86
- Chrome-only, directory input, 13 rules (PERM001-005, MV3001-005, FUNC001-002, SEC001).
89
+ Chrome-only, directory or `.zip`/`.crx` input, 17 rules (PERM001-005, MV3001-005, FUNC001-002,
90
+ SEC001, OBF001, PKG001-003).
87
91
 
88
92
  MV3001 (remotely hosted code, `reject`) covers HTML `<script src="https://…">`, remote
89
93
  `import`/`import()`, remote `importScripts()`, a remote `src` set on a
@@ -97,7 +101,9 @@ computed URLs.
97
101
  MV3005 (latent remote-code loader) covers what MV3001 deliberately leaves out: bundled
98
102
  code that *could* load a remote script. A `<script>` element (or `importScripts`) given
99
103
  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;
104
+ (`"https://cdn/" + v`, including a prefix held in a variable bound only to that string,
105
+ `var base = "https://cdn/"; s.src = base + "x.js"`) or the same file also contains a
106
+ remote `.js`/`.mjs` URL literal;
101
107
  the finding names the URL and, when a banner or `vendor/` path identifies it, the
102
108
  bundled package. Other remote `.js` URL literals in shipped code are `info` (they never
103
109
  change the verdict). Only `.js`/`.mjs` URLs count, so remote JSON/data endpoints are
@@ -110,7 +116,41 @@ that `remove`/`set` `Content-Security-Policy`(-Report-Only), `X-Frame-Options`,
110
116
  `fix` when the condition isn't scoped to specific domains and the extension has broad
111
117
  host access, otherwise `info`.
112
118
 
113
- Firefox/Edge, ZIP/CRX input, SARIF, and a GitHub Action are on the roadmap.
119
+ OBF001 (obfuscated code, Red Titanium, `fix`) looks for fingerprints that minifiers
120
+ never produce: `_0x`-style hexadecimal identifiers in quantity, javascript-obfuscator's
121
+ string-array rotator and hex-index lookups, Dean Edwards' `eval(function(p,a,c,k,e,d)…)`
122
+ packer, `eval`/`Function` run on a decoded string (`eval(atob(…))`,
123
+ `new Function(String.fromCharCode(…))`), and plain-text strings spelled with `\x`/`\u`
124
+ escapes. One finding per file, naming the bundled package from its license banner,
125
+ `node_modules/` or `vendor/` path, or the bundler's module comment. Measured precision:
126
+ 0 findings on 43 popular npm browser packages (lodash, react-dom, vue, chart.js, three,
127
+ pdf.js, @babel/standalone, crypto libraries, ... — 12,041 script files), the 7 minified
128
+ release extensions and the Google samples; 37 of 38 obfuscated samples flagged.
129
+
130
+ **Archive input (`.zip`/`.crx`).** Pass the zip you upload to the Chrome Web Store (or a
131
+ CRX2/CRX3 file: header, then zip) and every rule runs on exactly what ships. The reader
132
+ uses only Node built-ins (no new dependency); it never writes outside a private temp
133
+ directory, never follows symlinks, refuses ZIP64/encrypted entries, and caps extracted
134
+ code at 512 MiB. Inside an archive, `build/`/`dist/` folders are scanned like any other
135
+ code because they ship. If `manifest.json` sits inside a folder in the zip (the classic
136
+ "zipped the folder, not its contents" mistake) you get exit 3 with that explanation.
137
+ The package rules:
138
+
139
+ | Rule | Severity | What it flags |
140
+ |---|---|---|
141
+ | PKG001 | `fix` | `.env*` files, private keys (`*.pem`), `.git`/`.svn`/`.hg`, `node_modules/`, or entries with unsafe (`../`, absolute) paths inside the archive. `node_modules` files the manifest actually loads drop it to `info` |
142
+ | PKG001 | `info` | source maps (allowed, but they publish your source), test folders/`*.test.js`/`*.spec.js`, OS junk (`.DS_Store`, `__MACOSX/`, `Thumbs.db`) |
143
+ | PKG002 | `info` | `"key"` in manifest.json (a development-only stable-ID field), for directories too |
144
+ | PKG003 | `reject` / `info` | archive over the 2 GB package limit / within 10% of it |
145
+
146
+ PKG001 and PKG003 run on archive input only: a source directory normally contains
147
+ `node_modules`, `.git` and tests that never get zipped. Measured: the 295 Google sample
148
+ directories with a valid manifest (zipped), 6 real release zips and 2 Chrome Web Store
149
+ CRX downloads all gave the same verdict and the same non-PKG findings as the unpacked
150
+ directory (a 7th release zip, uBlock's, nests `manifest.json` in a folder and is
151
+ correctly refused). The only PKG001 hits were real test folders (`info`).
152
+
153
+ Firefox/Edge, SARIF, and a GitHub Action are on the roadmap.
114
154
 
115
155
  Two rules are intentionally conservative in v0.1 (trust is the product): **PERM001**
116
156
  (unused permission) and **MV3002** (string execution: `eval`/`new Function`) both ship
package/dist/cli.js CHANGED
@@ -2,12 +2,12 @@
2
2
  import { readFileSync, realpathSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { dirname, join } from "node:path";
5
- import { analyze } from "./engine/analyze.js";
5
+ import { analyzeInput } from "./engine/analyze.js";
6
6
  import { ManifestError } from "./engine/manifest.js";
7
7
  import { verdictExitCode } from "./engine/verdict.js";
8
8
  import { renderHuman } from "./reporters/human.js";
9
9
  import { renderJson } from "./reporters/json.js";
10
- const USAGE = "Usage: tabsmith-lint <extension-dir> [--format human|json] [--browser chrome] [--min-severity reject|fix|info]";
10
+ const USAGE = "Usage: tabsmith-lint <extension-dir | extension.zip | extension.crx> [--format human|json] [--browser chrome] [--min-severity reject|fix|info]";
11
11
  function version() {
12
12
  try {
13
13
  const here = dirname(fileURLToPath(import.meta.url));
@@ -20,14 +20,19 @@ function version() {
20
20
  function helpText() {
21
21
  return `tabsmith-lint v${version()} - pre-submission compliance linter for Manifest V3 Chrome extensions
22
22
 
23
- Point it at an unpacked extension directory and it flags likely Chrome Web Store
24
- rejection risks before you submit:
23
+ Point it at an unpacked extension directory, or at the .zip/.crx you upload, and it
24
+ flags likely Chrome Web Store 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
27
  import, importScripts, chrome.scripting remote files), latent remote-code loaders
28
28
  in bundled code, string execution, forbidden extension-page CSP, Manifest V2
29
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
30
32
  - broken packaging: missing or wrong-case file references
33
+ - package hygiene (.zip/.crx input): .env files, private keys, .git, node_modules,
34
+ source maps, tests and OS junk inside the upload; the 2 GB size limit; a leftover
35
+ manifest "key"; manifest.json not at the zip root
31
36
 
32
37
  ${USAGE}
33
38
 
@@ -66,7 +71,7 @@ export function run(argv) {
66
71
  return { exitCode: 3, stderr: `Unexpected argument: ${arg}\n${USAGE}` };
67
72
  }
68
73
  if (!dir)
69
- return { exitCode: 3, stderr: `No extension directory provided.\n${USAGE}` };
74
+ return { exitCode: 3, stderr: `No extension directory or .zip/.crx provided.\n${USAGE}` };
70
75
  if (browser !== "chrome")
71
76
  return { exitCode: 3, stderr: `Only --browser chrome is currently supported (got "${browser}").` };
72
77
  if (!["human", "json"].includes(format))
@@ -75,7 +80,7 @@ export function run(argv) {
75
80
  return { exitCode: 3, stderr: `Invalid --min-severity "${minSeverity}" (expected reject|fix|info).` };
76
81
  let report;
77
82
  try {
78
- report = analyze(dir, { version: version(), minSeverity });
83
+ report = analyzeInput(dir, { version: version(), minSeverity });
79
84
  }
80
85
  catch (e) {
81
86
  const msg = e instanceof ManifestError ? e.message : e.message;
@@ -1,4 +1,5 @@
1
- import { loadManifest } from "./manifest.js";
1
+ import { loadManifest, ManifestError } from "./manifest.js";
2
+ import { extractArchive, isArchivePath } from "./archive.js";
2
3
  import { discoverFiles, isScript, isHtml, isWithinRoot, refToRelPath } from "./file-discovery.js";
3
4
  import { existsSync, readFileSync, statSync } from "node:fs";
4
5
  import { join } from "node:path";
@@ -8,13 +9,49 @@ import { parseScript } from "../parse/parse-script.js";
8
9
  import { extractFromScripts } from "../parse/extract-api-calls.js";
9
10
  import { runRules } from "../rules/index.js";
10
11
  import { computeVerdict, filterByMinSeverity } from "./verdict.js";
12
+ /** CLI entry point: a directory, or a .zip/.crx exactly as uploaded to the
13
+ * Chrome Web Store. Archives are extracted to a temp dir (code/JSON content
14
+ * only; other files become empty placeholders) and removed afterwards. */
15
+ export function analyzeInput(inputPath, options) {
16
+ if (!isArchivePath(inputPath) || (existsSync(inputPath) && statSync(inputPath).isDirectory())) {
17
+ return analyze(inputPath, options);
18
+ }
19
+ if (!existsSync(inputPath) || !statSync(inputPath).isFile()) {
20
+ throw new ManifestError(`Archive not found: ${inputPath}`);
21
+ }
22
+ const extracted = extractArchive(inputPath);
23
+ try {
24
+ const { listing } = extracted;
25
+ const paths = listing.entries.map((e) => e.relPath);
26
+ if (!paths.includes("manifest.json")) {
27
+ const nested = paths.filter((p) => /^[^/]+\/manifest\.json$/.test(p));
28
+ const hint = nested.length
29
+ ? ` Found ${nested[0]}: the Chrome Web Store requires manifest.json at the ROOT of the zip, not inside a folder. Zip the folder's contents, not the folder.`
30
+ : "";
31
+ throw new ManifestError(`No manifest.json at the root of ${inputPath}.${hint}`);
32
+ }
33
+ return analyze(extracted.dir, {
34
+ ...options,
35
+ inputPath,
36
+ package: {
37
+ kind: listing.kind,
38
+ archiveBytes: listing.fileSize,
39
+ files: listing.entries.map((e) => ({ relPath: e.relPath, size: e.size, compressedSize: e.compressedSize })),
40
+ unsafePaths: listing.unsafePaths,
41
+ },
42
+ });
43
+ }
44
+ finally {
45
+ extracted.cleanup();
46
+ }
47
+ }
11
48
  /** Pure-ish engine entry point: directory in → LintReport out. Only manifest
12
49
  * loading and file discovery touch the filesystem. Throws ManifestError (→ CLI
13
50
  * exit 3) when the manifest is missing or invalid. */
14
51
  export function analyze(rootDir, options) {
15
52
  const { manifest, raw } = loadManifest(rootDir);
16
53
  const manifestRefs = collectManifestRefs(manifest);
17
- const files = discoverFiles(rootDir, manifestRefs);
54
+ const files = discoverFiles(rootDir, manifestRefs, { archive: !!options.package });
18
55
  const htmlFiles = files.filter((f) => isHtml(f.relPath));
19
56
  const scriptFiles = files.filter((f) => isScript(f.relPath)).map(parseScript);
20
57
  const extraction = extractFromScripts(scriptFiles);
@@ -37,6 +74,7 @@ export function analyze(rootDir, options) {
37
74
  manifestRefs: manifestRefs.all,
38
75
  runtimeRequestedPermissions: extraction.runtimeRequestedPermissions,
39
76
  dnrRulesets: loadDnrRulesets(rootDir, manifest),
77
+ ...(options.package ? { package: options.package } : {}),
40
78
  };
41
79
  const ruleFindings = runRules(model);
42
80
  const parseFindings = scriptFiles
@@ -61,13 +99,14 @@ export function analyze(rootDir, options) {
61
99
  return {
62
100
  tool: "tabsmith-lint",
63
101
  version: options.version,
64
- inputPath: rootDir,
102
+ inputPath: options.inputPath ?? rootDir,
65
103
  manifestVersion: manifest.manifest_version,
66
104
  browsers: {
67
105
  chrome: {
68
106
  verdict,
69
107
  findings,
70
108
  stats: {
109
+ ...(options.package ? { packageFiles: options.package.files.length } : {}),
71
110
  filesScanned: files.length,
72
111
  scriptsParsed,
73
112
  parseErrors: scriptFiles.length - scriptsParsed,
@@ -0,0 +1,219 @@
1
+ import { openSync, readSync, closeSync, fstatSync, mkdirSync, writeFileSync, mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join, dirname } from "node:path";
4
+ import { inflateRawSync } from "node:zlib";
5
+ import { ManifestError } from "./manifest.js";
6
+ const EOCD_SIG = 0x06054b50;
7
+ const CEN_SIG = 0x02014b50;
8
+ const LOC_SIG = 0x04034b50;
9
+ export function isArchivePath(p) {
10
+ return /\.(zip|crx)$/i.test(p);
11
+ }
12
+ function readAt(fd, pos, len) {
13
+ const buf = Buffer.alloc(len);
14
+ let off = 0;
15
+ while (off < len) {
16
+ const n = readSync(fd, buf, off, len - off, pos + off);
17
+ if (n === 0)
18
+ break;
19
+ off += n;
20
+ }
21
+ return off === len ? buf : buf.subarray(0, off);
22
+ }
23
+ /** Normalize an entry name to a safe POSIX relative path, or null when it would
24
+ * escape the package (absolute, drive-letter, or ".." segments). */
25
+ export function safeEntryPath(name) {
26
+ const p = name.replace(/\\/g, "/");
27
+ if (p.startsWith("/") || /^[a-zA-Z]:/.test(p))
28
+ return null;
29
+ const parts = [];
30
+ for (const seg of p.split("/")) {
31
+ if (seg === "" || seg === ".")
32
+ continue;
33
+ if (seg === "..")
34
+ return null;
35
+ parts.push(seg);
36
+ }
37
+ return parts.length ? parts.join("/") : null;
38
+ }
39
+ /** Byte length of a CRX header (0 for a plain zip). Throws on a bad CRX. */
40
+ function crxHeaderLength(fd, fileSize) {
41
+ const head = readAt(fd, 0, Math.min(16, fileSize));
42
+ if (head.length < 4 || head.toString("latin1", 0, 4) !== "Cr24")
43
+ return { kind: "zip", skip: 0 };
44
+ if (head.length < 12)
45
+ throw new ManifestError("Truncated CRX header");
46
+ const version = head.readUInt32LE(4);
47
+ if (version === 3)
48
+ return { kind: "crx", skip: 12 + head.readUInt32LE(8) };
49
+ if (version === 2) {
50
+ if (head.length < 16)
51
+ throw new ManifestError("Truncated CRX2 header");
52
+ return { kind: "crx", skip: 16 + head.readUInt32LE(8) + head.readUInt32LE(12) };
53
+ }
54
+ throw new ManifestError(`Unsupported CRX version ${version}`);
55
+ }
56
+ /** List the entries of a .zip/.crx without extracting anything. */
57
+ export function listArchive(path) {
58
+ let fd;
59
+ try {
60
+ fd = openSync(path, "r");
61
+ }
62
+ catch (e) {
63
+ throw new ManifestError(`Could not open archive: ${e.message}`);
64
+ }
65
+ try {
66
+ return listFd(fd);
67
+ }
68
+ finally {
69
+ closeSync(fd);
70
+ }
71
+ }
72
+ function listFd(fd) {
73
+ const fileSize = fstatSync(fd).size;
74
+ const { kind, skip } = crxHeaderLength(fd, fileSize);
75
+ if (skip > fileSize)
76
+ throw new ManifestError("CRX header is larger than the file");
77
+ // End of central directory: last 22 bytes + up to 64 KiB comment.
78
+ const tailLen = Math.min(fileSize - skip, 22 + 0xffff);
79
+ if (tailLen < 22)
80
+ throw new ManifestError("Not a zip archive (too small)");
81
+ const tailStart = fileSize - tailLen;
82
+ const tail = readAt(fd, tailStart, tailLen);
83
+ let eocd = -1;
84
+ for (let i = tail.length - 22; i >= 0; i--) {
85
+ if (tail.readUInt32LE(i) === EOCD_SIG) {
86
+ eocd = i;
87
+ break;
88
+ }
89
+ }
90
+ if (eocd < 0)
91
+ throw new ManifestError("Not a zip archive (no end-of-central-directory record)");
92
+ const disk = tail.readUInt16LE(eocd + 4);
93
+ const total = tail.readUInt16LE(eocd + 10);
94
+ const cdSize = tail.readUInt32LE(eocd + 12);
95
+ const cdOffset = tail.readUInt32LE(eocd + 16);
96
+ if (disk !== 0)
97
+ throw new ManifestError("Multi-disk zip archives are not supported");
98
+ if (total === 0xffff || cdSize === 0xffffffff || cdOffset === 0xffffffff) {
99
+ throw new ManifestError("ZIP64 archives are not supported");
100
+ }
101
+ const eocdPos = tailStart + eocd;
102
+ // Tolerate data prepended to the zip (CRX header, self-extractor stubs):
103
+ // central-directory offsets are relative to where the zip itself starts.
104
+ const base = eocdPos - cdSize - cdOffset;
105
+ if (base < 0 || eocdPos - cdSize < skip)
106
+ throw new ManifestError("Corrupt zip archive (bad central directory offset)");
107
+ const cd = readAt(fd, base + cdOffset, cdSize);
108
+ const entries = new Map();
109
+ const unsafePaths = [];
110
+ let p = 0;
111
+ for (let n = 0; n < total; n++) {
112
+ if (p + 46 > cd.length || cd.readUInt32LE(p) !== CEN_SIG)
113
+ throw new ManifestError("Corrupt zip archive (bad central directory entry)");
114
+ const flags = cd.readUInt16LE(p + 8);
115
+ const method = cd.readUInt16LE(p + 10);
116
+ const compressedSize = cd.readUInt32LE(p + 20);
117
+ const size = cd.readUInt32LE(p + 24);
118
+ const nameLen = cd.readUInt16LE(p + 28);
119
+ const extraLen = cd.readUInt16LE(p + 30);
120
+ const commentLen = cd.readUInt16LE(p + 32);
121
+ const externalAttrs = cd.readUInt32LE(p + 38);
122
+ const localOffset = cd.readUInt32LE(p + 42);
123
+ const rawName = cd.subarray(p + 46, p + 46 + nameLen);
124
+ // bit 11 = UTF-8 names; otherwise CP437, which matches ASCII for real-world names.
125
+ const name = rawName.toString(flags & 0x800 ? "utf8" : "latin1");
126
+ p += 46 + nameLen + extraLen + commentLen;
127
+ if (flags & 0x1)
128
+ throw new ManifestError(`Encrypted zip entries are not supported (${name})`);
129
+ if (size === 0xffffffff || compressedSize === 0xffffffff || localOffset === 0xffffffff) {
130
+ throw new ManifestError("ZIP64 archives are not supported");
131
+ }
132
+ if (name.endsWith("/") || name.endsWith("\\"))
133
+ continue; // directory entry
134
+ const rel = safeEntryPath(name);
135
+ if (rel === null) {
136
+ unsafePaths.push(name);
137
+ continue;
138
+ }
139
+ const mode = externalAttrs >>> 16;
140
+ entries.set(rel, {
141
+ relPath: rel,
142
+ size,
143
+ compressedSize,
144
+ method,
145
+ localHeaderOffset: base + localOffset,
146
+ symlink: (mode & 0o170000) === 0o120000,
147
+ });
148
+ }
149
+ return { kind, fileSize, entries: [...entries.values()], unsafePaths };
150
+ }
151
+ function readEntryData(fd, e) {
152
+ const loc = readAt(fd, e.localHeaderOffset, 30);
153
+ if (loc.length < 30 || loc.readUInt32LE(0) !== LOC_SIG)
154
+ throw new ManifestError(`Corrupt zip archive (bad local header for ${e.relPath})`);
155
+ const dataStart = e.localHeaderOffset + 30 + loc.readUInt16LE(26) + loc.readUInt16LE(28);
156
+ const raw = readAt(fd, dataStart, e.compressedSize);
157
+ if (raw.length !== e.compressedSize)
158
+ throw new ManifestError(`Corrupt zip archive (truncated data for ${e.relPath})`);
159
+ if (e.method === 0)
160
+ return raw;
161
+ if (e.method === 8) {
162
+ try {
163
+ return inflateRawSync(raw, { maxOutputLength: Math.max(e.size, 1) });
164
+ }
165
+ catch (err) {
166
+ throw new ManifestError(`Could not inflate ${e.relPath}: ${err.message}`);
167
+ }
168
+ }
169
+ throw new ManifestError(`Unsupported zip compression method ${e.method} (${e.relPath})`);
170
+ }
171
+ /** Files whose CONTENT the engine reads; everything else (images, fonts, wasm…)
172
+ * is materialized as an empty placeholder so existence checks still work. */
173
+ const CONTENT_EXT = /\.(js|mjs|cjs|ts|tsx|jsx|html?|json)$/i;
174
+ /** Per-file and total caps on extracted content, a guard against zip bombs. */
175
+ export const MAX_ENTRY_BYTES = 64 * 1024 * 1024;
176
+ export const MAX_TOTAL_BYTES = 512 * 1024 * 1024;
177
+ /** Extract a .zip/.crx into a fresh temp directory for analysis. Never follows
178
+ * or creates symlinks, never writes outside the temp dir. */
179
+ export function extractArchive(path) {
180
+ let fd;
181
+ try {
182
+ fd = openSync(path, "r");
183
+ }
184
+ catch (e) {
185
+ throw new ManifestError(`Could not open archive: ${e.message}`);
186
+ }
187
+ const dir = mkdtempSync(join(tmpdir(), "tabsmith-pkg-"));
188
+ const cleanup = () => rmSync(dir, { recursive: true, force: true });
189
+ try {
190
+ const listing = listFd(fd);
191
+ const dirs = new Set(listing.entries.flatMap((e) => {
192
+ const parts = e.relPath.split("/");
193
+ return parts.slice(1).map((_, i) => parts.slice(0, i + 1).join("/"));
194
+ }));
195
+ let total = 0;
196
+ for (const e of listing.entries) {
197
+ if (dirs.has(e.relPath))
198
+ continue; // file/dir name clash: keep the directory
199
+ const abs = join(dir, ...e.relPath.split("/"));
200
+ mkdirSync(dirname(abs), { recursive: true });
201
+ let data = Buffer.alloc(0);
202
+ if (!e.symlink && CONTENT_EXT.test(e.relPath) && e.size <= MAX_ENTRY_BYTES) {
203
+ total += e.size;
204
+ if (total > MAX_TOTAL_BYTES)
205
+ throw new ManifestError("Archive expands to more than 512 MiB of code/JSON; refusing to extract");
206
+ data = readEntryData(fd, e);
207
+ }
208
+ writeFileSync(abs, data);
209
+ }
210
+ return { listing, dir, cleanup };
211
+ }
212
+ catch (e) {
213
+ cleanup();
214
+ throw e;
215
+ }
216
+ finally {
217
+ closeSync(fd);
218
+ }
219
+ }
@@ -5,6 +5,10 @@ const SCRIPT_EXT = [".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"];
5
5
  const HTML_EXT = [".html", ".htm"];
6
6
  const SCANNABLE = new Set([...SCRIPT_EXT, ...HTML_EXT]);
7
7
  const EXCLUDE_DIRS = new Set(["node_modules", ".git", "dist", "build", ".cache", "coverage"]);
8
+ /** Inside an uploaded archive everything ships, so build-output folders are real
9
+ * package code and must be scanned. node_modules/.git are still skipped for code
10
+ * analysis (PKG001 reports them as files that should not ship). */
11
+ const ARCHIVE_EXCLUDE_DIRS = new Set(["node_modules", ".git"]);
8
12
  function ext(path) {
9
13
  const i = path.lastIndexOf(".");
10
14
  return i < 0 ? "" : path.slice(i).toLowerCase();
@@ -56,12 +60,14 @@ function localScriptSrcs(htmlContent, htmlRel) {
56
60
  /**
57
61
  * Two-pass discovery: manifest-directed entry points first (tagged "manifest"),
58
62
  * then a package-wide fallback scan (tagged "fallback"). Manifest tags win on
59
- * dedupe. node_modules/.git/build caches and source maps are excluded.
63
+ * dedupe. node_modules/.git/build caches and source maps are excluded (inside an
64
+ * extracted archive only node_modules/.git are, because build output ships).
60
65
  *
61
66
  * Takes pre-collected ManifestRefs so the caller can reuse them (e.g. for
62
67
  * model.manifestRefs) without collecting twice.
63
68
  */
64
- export function discoverFiles(rootDir, refs) {
69
+ export function discoverFiles(rootDir, refs, options = {}) {
70
+ const exclude = options.archive ? ARCHIVE_EXCLUDE_DIRS : EXCLUDE_DIRS;
65
71
  const byRel = new Map();
66
72
  const add = (vf) => {
67
73
  if (!vf)
@@ -83,7 +89,7 @@ export function discoverFiles(rootDir, refs) {
83
89
  }
84
90
  }
85
91
  // --- Pass 2: fallback scan ---
86
- walk(rootDir, rootDir, (abs) => {
92
+ walk(rootDir, rootDir, exclude, (abs) => {
87
93
  const rel = toRel(rootDir, abs);
88
94
  if (rel === "manifest.json")
89
95
  return;
@@ -100,7 +106,7 @@ export function discoverFiles(rootDir, refs) {
100
106
  });
101
107
  return [...byRel.values()];
102
108
  }
103
- function walk(rootDir, dir, onFile) {
109
+ function walk(rootDir, dir, exclude, onFile) {
104
110
  let entries;
105
111
  try {
106
112
  entries = readdirSync(dir, { withFileTypes: true });
@@ -111,9 +117,9 @@ function walk(rootDir, dir, onFile) {
111
117
  for (const e of entries) {
112
118
  const abs = join(dir, e.name);
113
119
  if (e.isDirectory()) {
114
- if (EXCLUDE_DIRS.has(e.name))
120
+ if (exclude.has(e.name))
115
121
  continue;
116
- walk(rootDir, abs, onFile);
122
+ walk(rootDir, abs, exclude, onFile);
117
123
  }
118
124
  else if (e.isFile()) {
119
125
  onFile(abs);
@@ -19,7 +19,8 @@ export function renderHuman(report, minSeverity = "info") {
19
19
  const lines = [];
20
20
  lines.push(`tabsmith-lint v${report.version} analyzing ${report.inputPath}`);
21
21
  const mv = report.manifestVersion !== undefined ? `Manifest V${report.manifestVersion}` : "Manifest version unknown";
22
- lines.push(`${mv}, ${chrome.stats.filesScanned} files scanned, ${chrome.stats.scriptsParsed} scripts parsed`);
22
+ const pkg = chrome.stats.packageFiles !== undefined ? `${chrome.stats.packageFiles} files in package, ` : "";
23
+ lines.push(`${mv}, ${pkg}${chrome.stats.filesScanned} files scanned, ${chrome.stats.scriptsParsed} scripts parsed`);
23
24
  lines.push("");
24
25
  lines.push(`CHROME: ${VERDICT_HEADER[chrome.verdict]}`);
25
26
  lines.push("");
@@ -3,7 +3,9 @@ import { permissionRules } from "./permissions.js";
3
3
  import { mv3Rules } from "./mv3.js";
4
4
  import { fileRules } from "./files.js";
5
5
  import { securityRules } from "./security.js";
6
- export const allRules = [...permissionRules, ...mv3Rules, ...fileRules, ...securityRules];
6
+ import { obfuscationRules } from "./obfuscation.js";
7
+ import { packageRules } from "./package.js";
8
+ export const allRules = [...permissionRules, ...mv3Rules, ...fileRules, ...securityRules, ...obfuscationRules, ...packageRules];
7
9
  /** Run every rule and return all findings, ordered reject → fix → info. */
8
10
  export function runRules(model) {
9
11
  const findings = allRules.flatMap((rule) => rule(model));
package/dist/rules/mv3.js CHANGED
@@ -119,20 +119,31 @@ function patternNames(pattern, out = []) {
119
119
  }
120
120
  return out;
121
121
  }
122
- /** Names bound ONLY to document.createElement("script") anywhere in the file. */
123
- function scriptElementNames(ast) {
124
- 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();
125
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
+ };
126
135
  walk(ast, (node) => {
127
136
  if (node.type === "VariableDeclarator") {
128
- if (node.id?.type === "Identifier" && isScriptCreate(node.init))
129
- 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);
130
140
  else if (node.init)
131
141
  patternNames(node.id).forEach((n) => other.add(n));
132
142
  }
133
143
  else if (node.type === "AssignmentExpression" && node.left?.type === "Identifier") {
134
- if (node.operator === "=" && isScriptCreate(node.right))
135
- script.add(node.left.name);
144
+ const v = node.operator === "=" ? valueOf(node.right) : null;
145
+ if (v !== null)
146
+ record(node.left.name, v);
136
147
  else
137
148
  other.add(node.left.name);
138
149
  }
@@ -165,8 +176,16 @@ function scriptElementNames(ast) {
165
176
  }
166
177
  });
167
178
  for (const n of other)
168
- script.delete(n);
169
- return script;
179
+ bound.delete(n);
180
+ return bound;
181
+ }
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));
170
189
  }
171
190
  /** Every place a `document.createElement("script")` element gets its `src` set,
172
191
  * literal or not: `.src =`, `["src"] =`, `setAttribute("src", …)`,
@@ -378,14 +397,22 @@ function isGetUrlCall(node) {
378
397
  c.object.property?.type === "Identifier" &&
379
398
  (c.object.property.name === "runtime" || c.object.property.name === "extension"));
380
399
  }
381
- /** Leading static text of a string-building expression ("a" + x, `a${x}`). */
382
- function staticPrefix(node) {
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) {
383
404
  if (node?.type === "StringLiteral")
384
405
  return node.value;
385
- if (node?.type === "TemplateLiteral")
386
- return node.quasis?.[0]?.value?.cooked ?? null;
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
+ }
387
414
  if (node?.type === "BinaryExpression" && node.operator === "+")
388
- return staticPrefix(node.left);
415
+ return staticPrefix(node.left, consts);
389
416
  return null;
390
417
  }
391
418
  const BANNER_RE = /^\s*(?:\/\*[!*]?|\/\/)\s*(?:@license\s+)?(@?[A-Za-z][\w./-]*)\s+v?(\d+\.\d+\.\d+[\w.-]*)/;
@@ -437,12 +464,18 @@ function mv3005(model) {
437
464
  // One `fix` finding per file (first loader), other loader lines listed, to keep bundles readable.
438
465
  let latent = false;
439
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
440
469
  for (const { node, value, how } of sinks) {
441
470
  if (isGetUrlCall(value))
442
471
  continue;
443
- const prefix = staticPrefix(value);
472
+ const prefix = staticPrefix(value, consts);
444
473
  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.` });
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.` });
446
479
  }
447
480
  else if (urls.length > 0) {
448
481
  latent = true;
@@ -467,15 +500,16 @@ function mv3005(model) {
467
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.",
468
501
  });
469
502
  }
470
- if (!latent && urls.length > 0) {
503
+ const unexplained = urls.filter((u) => !prefixes.has(u));
504
+ if (!latent && unexplained.length > 0) {
471
505
  findings.push({
472
506
  ruleId: "MV3005",
473
507
  severity: "info",
474
508
  confidence: "low",
475
509
  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}`,
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}`,
477
511
  file,
478
- line: literals[0]?.line,
512
+ line: literals.find((l) => !prefixes.has(l.url))?.line,
479
513
  chromeViolationId: "Blue Argon",
480
514
  fixHint: "Remove unused remote script URLs at build time, or explain them in the submission notes.",
481
515
  });
@@ -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,197 @@
1
+ import { findLine } from "../engine/source-lines.js";
2
+ // Package hygiene: what is inside the .zip/.crx you actually upload.
3
+ // PKG001 — files that should not ship (secrets, VCS metadata, node_modules,
4
+ // private keys, unsafe entry paths at `fix`; source maps, tests and OS
5
+ // junk at `info`). Runs on .zip/.crx input only: an unpacked SOURCE
6
+ // directory normally contains node_modules/.git/tests that never get
7
+ // zipped, so judging a directory would be all false positives.
8
+ // PKG002 — "key" left in manifest.json (`info`, any input). It pins a stable ID
9
+ // for unpacked development; the store assigns the published ID.
10
+ // PKG003 — archive larger than the Chrome Web Store's 2 GB package limit
11
+ // ("Zip files larger than 2GB will be rejected") → `reject`; within
12
+ // 10% of it → `info`.
13
+ export const PACKAGE_LIMIT_BYTES = 2 * 1024 * 1024 * 1024;
14
+ const NEAR_LIMIT_BYTES = Math.floor(PACKAGE_LIMIT_BYTES * 0.9);
15
+ const SHOW_PATHS = 5;
16
+ // "spec" is deliberately absent: editors ship runtime language modes in folders
17
+ // named spec (CodeMirror mode/rpm/spec/spec.js), found on the samples corpus.
18
+ const TEST_DIRS = new Set(["test", "tests", "__tests__", "__mocks__", "e2e", "cypress"]);
19
+ const VCS_DIRS = new Set([".git", ".svn", ".hg"]);
20
+ const OS_JUNK = new Set([".ds_store", "thumbs.db", "desktop.ini"]);
21
+ const CATEGORIES = [
22
+ {
23
+ id: "env",
24
+ severity: "fix",
25
+ confidence: "high",
26
+ title: ".env file(s) in the package",
27
+ why: "Environment files usually hold API keys and other secrets; anything in the package is public to every user who installs it.",
28
+ fixHint: "Remove .env* files from the zip (and rotate any secret that already shipped). Inject build-time values instead.",
29
+ match: (_r, _s, base) => /^\.env(\..+)?$/i.test(base),
30
+ },
31
+ {
32
+ id: "key",
33
+ severity: "fix",
34
+ confidence: "high",
35
+ title: "Private key (.pem) in the package",
36
+ why: "A .pem file is typically the extension's CRX signing key or another private key; shipping it exposes it publicly.",
37
+ fixHint: "Remove the .pem from the zip and keep it outside the extension folder. If it is a signing key that shipped, treat it as compromised.",
38
+ match: (_r, _s, base) => /\.pem$/i.test(base),
39
+ },
40
+ {
41
+ id: "vcs",
42
+ severity: "fix",
43
+ confidence: "high",
44
+ title: "Version-control metadata in the package",
45
+ why: "A .git/.svn/.hg folder ships your repository history (possibly including removed secrets) and bloats the upload.",
46
+ fixHint: "Zip the build output, not the repository checkout; exclude .git/.svn/.hg.",
47
+ match: (_r, segs) => segs.slice(0, -1).some((s) => VCS_DIRS.has(s)),
48
+ },
49
+ {
50
+ id: "node_modules",
51
+ severity: "fix",
52
+ confidence: "high",
53
+ title: "node_modules/ in the package",
54
+ why: "node_modules is development input: it bloats the package and ships code reviewers must audit, including dependencies the extension never loads.",
55
+ fixHint: "Bundle what you use (esbuild/Vite/webpack) or copy the specific files into your build output, then zip only the output.",
56
+ match: (_r, segs) => segs.slice(0, -1).includes("node_modules"),
57
+ },
58
+ {
59
+ id: "sourcemap",
60
+ severity: "info",
61
+ confidence: "high",
62
+ title: "Source maps in the package",
63
+ why: "Source maps are allowed, but they publish your original source and add size. Keep them only if that is intentional (they can help reviewers read minified code).",
64
+ fixHint: "Disable production source maps or strip *.map files from the zip if you do not mean to ship them.",
65
+ match: (_r, _s, base) => /\.map$/i.test(base),
66
+ },
67
+ {
68
+ id: "tests",
69
+ severity: "info",
70
+ confidence: "medium",
71
+ title: "Test files in the package",
72
+ why: "Test files and fixtures are not used at runtime; they add size and code for reviewers to read.",
73
+ fixHint: "Exclude test/spec files and folders from the zip.",
74
+ match: (_r, segs, base) => segs.slice(0, -1).some((s) => TEST_DIRS.has(s.toLowerCase())) || /\.(test|spec)\.[cm]?[jt]sx?$/i.test(base),
75
+ },
76
+ {
77
+ id: "junk",
78
+ severity: "info",
79
+ confidence: "high",
80
+ title: "OS junk files in the package",
81
+ why: "Finder/Explorer metadata (.DS_Store, __MACOSX/, Thumbs.db) is clutter that ships to every user.",
82
+ fixHint: "Zip with `zip -r ext.zip . -x '.DS_Store' '__MACOSX/*'` or your build tool, or delete these files before zipping.",
83
+ match: (_r, segs, base) => OS_JUNK.has(base.toLowerCase()) || segs[0] === "__MACOSX",
84
+ },
85
+ ];
86
+ function listPaths(paths) {
87
+ const shown = paths.slice(0, SHOW_PATHS).join(", ");
88
+ return paths.length > SHOW_PATHS ? `${shown} (+${paths.length - SHOW_PATHS} more)` : shown;
89
+ }
90
+ /** Files the extension actually loads (manifest entries and the scripts their
91
+ * pages include). A referenced file is never reported as "should not ship". */
92
+ function referencedPaths(model) {
93
+ const out = new Set();
94
+ for (const r of model.manifestRefs)
95
+ out.add(r.ref.replace(/^[\\/]+/, ""));
96
+ for (const f of model.files)
97
+ if (f.discoveredBy === "manifest")
98
+ out.add(f.relPath);
99
+ return out;
100
+ }
101
+ function packageContents(model) {
102
+ const pkg = model.package;
103
+ if (!pkg)
104
+ return [];
105
+ const findings = [];
106
+ const referenced = referencedPaths(model);
107
+ const claimed = new Set();
108
+ for (const cat of CATEGORIES) {
109
+ const hits = [];
110
+ const used = [];
111
+ for (const f of pkg.files) {
112
+ if (claimed.has(f.relPath))
113
+ continue;
114
+ const segs = f.relPath.split("/");
115
+ if (!cat.match(f.relPath, segs, segs[segs.length - 1]))
116
+ continue;
117
+ claimed.add(f.relPath);
118
+ (referenced.has(f.relPath) ? used : hits).push(f.relPath);
119
+ }
120
+ if (hits.length === 0)
121
+ continue;
122
+ // node_modules the extension really loads (e.g. a polyfill referenced from the
123
+ // manifest): removing the folder would break it, so only advise.
124
+ const severity = cat.id === "node_modules" && used.length > 0 ? "info" : cat.severity;
125
+ const usedNote = used.length ? ` ${used.length} referenced file(s) there are loaded by the extension (${listPaths(used)}); move them into your build output before dropping the rest.` : "";
126
+ findings.push({
127
+ ruleId: "PKG001",
128
+ severity,
129
+ confidence: cat.confidence,
130
+ title: cat.title,
131
+ message: `${hits.length} file(s): ${listPaths(hits)}. ${cat.why}${usedNote}`,
132
+ file: hits[0],
133
+ fixHint: cat.fixHint,
134
+ });
135
+ }
136
+ if (pkg.unsafePaths.length) {
137
+ findings.push({
138
+ ruleId: "PKG001",
139
+ severity: "fix",
140
+ confidence: "high",
141
+ title: "Archive entries with unsafe paths",
142
+ message: `${pkg.unsafePaths.length} entr${pkg.unsafePaths.length === 1 ? "y" : "ies"} escape the package root and were skipped: ${listPaths(pkg.unsafePaths)}. Absolute or "../" paths are not valid in an extension package.`,
143
+ fixHint: "Re-create the zip from inside the extension folder with relative paths only.",
144
+ });
145
+ }
146
+ return findings;
147
+ }
148
+ function manifestKey(model) {
149
+ if (!Object.prototype.hasOwnProperty.call(model.manifest, "key"))
150
+ return [];
151
+ return [
152
+ {
153
+ ruleId: "PKG002",
154
+ severity: "info",
155
+ confidence: "high",
156
+ title: `"key" is set in manifest.json`,
157
+ message: `The "key" field pins a stable extension ID for unpacked development. The Chrome Web Store assigns the published item its own ID and key, so this is normally a development leftover.`,
158
+ file: "manifest.json",
159
+ line: findLine(model.manifestRaw, `"key"`),
160
+ fixHint: `Remove "key" from the manifest in the package you upload (keep it only in your development manifest).`,
161
+ },
162
+ ];
163
+ }
164
+ function gb(bytes) {
165
+ return `${(bytes / 1024 ** 3).toFixed(2)} GiB`;
166
+ }
167
+ function packageSize(model) {
168
+ const pkg = model.package;
169
+ if (!pkg)
170
+ return [];
171
+ if (pkg.archiveBytes > PACKAGE_LIMIT_BYTES) {
172
+ return [
173
+ {
174
+ ruleId: "PKG003",
175
+ severity: "reject",
176
+ confidence: "high",
177
+ title: "Package exceeds the Chrome Web Store 2 GB limit",
178
+ message: `The archive is ${gb(pkg.archiveBytes)}. The maximum supported package size is 2GB; larger zip files are rejected at upload.`,
179
+ fixHint: "Drop unused assets (and anything PKG001 lists), compress media, or download large data at runtime as data (not code).",
180
+ },
181
+ ];
182
+ }
183
+ if (pkg.archiveBytes > NEAR_LIMIT_BYTES) {
184
+ return [
185
+ {
186
+ ruleId: "PKG003",
187
+ severity: "info",
188
+ confidence: "high",
189
+ title: "Package is close to the Chrome Web Store 2 GB limit",
190
+ message: `The archive is ${gb(pkg.archiveBytes)}, within 10% of the 2GB package limit.`,
191
+ fixHint: "Trim unused assets before the next release pushes it over the limit.",
192
+ },
193
+ ];
194
+ }
195
+ return [];
196
+ }
197
+ export const packageRules = [packageContents, manifestKey, packageSize];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tabsmith-lint",
3
- "version": "0.4.0",
3
+ "version": "0.6.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": {