tabsmith-lint 0.5.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
@@ -28,11 +28,13 @@ Chrome reviewers flag:
28
28
  | Yellow Magnesium | Functionality / broken packaging | FUNC001, FUNC002 |
29
29
  | Red Titanium | Obfuscated code (minification is fine) | OBF001 |
30
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 |
31
32
 
32
33
  ```bash
33
34
  npx tabsmith-lint ./my-extension
34
35
  npx tabsmith-lint ./my-extension --format json
35
36
  npx tabsmith-lint ./my-extension --min-severity reject
37
+ npx tabsmith-lint ./my-extension.zip # lint exactly what you upload (.zip or .crx)
36
38
  ```
37
39
 
38
40
  Exit codes: `0` pass · `1` needs fixes · `2` high rejection risk · `3` tool error.
@@ -84,7 +86,8 @@ exists, leave the severity at `fix`.
84
86
 
85
87
  ## Status
86
88
 
87
- Chrome-only, directory input, 14 rules (PERM001-005, MV3001-005, FUNC001-002, SEC001, OBF001).
89
+ Chrome-only, directory or `.zip`/`.crx` input, 17 rules (PERM001-005, MV3001-005, FUNC001-002,
90
+ SEC001, OBF001, PKG001-003).
88
91
 
89
92
  MV3001 (remotely hosted code, `reject`) covers HTML `<script src="https://…">`, remote
90
93
  `import`/`import()`, remote `importScripts()`, a remote `src` set on a
@@ -124,7 +127,30 @@ escapes. One finding per file, naming the bundled package from its license banne
124
127
  pdf.js, @babel/standalone, crypto libraries, ... — 12,041 script files), the 7 minified
125
128
  release extensions and the Google samples; 37 of 38 obfuscated samples flagged.
126
129
 
127
- Firefox/Edge, ZIP/CRX input, SARIF, and a GitHub Action are on the roadmap.
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.
128
154
 
129
155
  Two rules are intentionally conservative in v0.1 (trust is the product): **PERM001**
130
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,8 +20,8 @@ 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
@@ -30,6 +30,9 @@ rejection risks before you submit:
30
30
  - obfuscated code ("Red Titanium": javascript-obfuscator output, packers, eval of
31
31
  decoded strings), naming the bundled package it comes from; minified code is fine
32
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
33
36
 
34
37
  ${USAGE}
35
38
 
@@ -68,7 +71,7 @@ export function run(argv) {
68
71
  return { exitCode: 3, stderr: `Unexpected argument: ${arg}\n${USAGE}` };
69
72
  }
70
73
  if (!dir)
71
- return { exitCode: 3, stderr: `No extension directory provided.\n${USAGE}` };
74
+ return { exitCode: 3, stderr: `No extension directory or .zip/.crx provided.\n${USAGE}` };
72
75
  if (browser !== "chrome")
73
76
  return { exitCode: 3, stderr: `Only --browser chrome is currently supported (got "${browser}").` };
74
77
  if (!["human", "json"].includes(format))
@@ -77,7 +80,7 @@ export function run(argv) {
77
80
  return { exitCode: 3, stderr: `Invalid --min-severity "${minSeverity}" (expected reject|fix|info).` };
78
81
  let report;
79
82
  try {
80
- report = analyze(dir, { version: version(), minSeverity });
83
+ report = analyzeInput(dir, { version: version(), minSeverity });
81
84
  }
82
85
  catch (e) {
83
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("");
@@ -4,7 +4,8 @@ import { mv3Rules } from "./mv3.js";
4
4
  import { fileRules } from "./files.js";
5
5
  import { securityRules } from "./security.js";
6
6
  import { obfuscationRules } from "./obfuscation.js";
7
- export const allRules = [...permissionRules, ...mv3Rules, ...fileRules, ...securityRules, ...obfuscationRules];
7
+ import { packageRules } from "./package.js";
8
+ export const allRules = [...permissionRules, ...mv3Rules, ...fileRules, ...securityRules, ...obfuscationRules, ...packageRules];
8
9
  /** Run every rule and return all findings, ordered reject → fix → info. */
9
10
  export function runRules(model) {
10
11
  const findings = allRules.flatMap((rule) => rule(model));
@@ -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.5.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": {