@jasonsdevspace/repo-check 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jason Poteet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,156 @@
1
- # Temporary Holding Version
1
+ # @jasonsdevspace/repo-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/@jasonsdevspace/repo-check)](https://www.npmjs.com/package/@jasonsdevspace/repo-check)
4
+ [![CI](https://github.com/jasonsdevspace/tooling/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/jasonsdevspace/tooling/actions/workflows/ci.yml)
5
+ [![MIT license](https://img.shields.io/npm/l/@jasonsdevspace/repo-check)](https://github.com/jasonsdevspace/tooling/blob/main/packages/repo-check/LICENSE)
6
+
7
+ The house's checks of a repository as a whole, each a command of its own. The first,
8
+ `check-installs`, fails a build wherever npm could run a package's install scripts or fetch a
9
+ dependency from git or a URL. An install script runs code from every package as it installs, before
10
+ any test has looked at it, which is how a compromised release spreads. npm's own settings stop every
11
+ one of them, however the install is written, so the check holds a repository to those settings
12
+ rather than reading the commands it runs.
13
+
14
+ [Changelog](https://github.com/jasonsdevspace/tooling/blob/main/packages/repo-check/CHANGELOG.md) ·
15
+ [Source](https://github.com/jasonsdevspace/tooling/tree/main/packages/repo-check)
16
+
17
+ ## The rule `check-installs` holds
18
+
19
+ - **Every package root holds a `.npmrc` that sets `ignore-scripts=true`, `allow-git=none` and
20
+ `allow-remote=none`.** The first stops install scripts. The other two stop npm fetching a
21
+ dependency from a git repository or a tarball's address, which npm's notes name as a way around
22
+ the first. A package root is the repository's root, and any folder with a `package.json` of its
23
+ own that no package above it lists as a workspace, such as a demo with its own dependencies. npm
24
+ reads a project's `.npmrc` from the root of the project it runs in, and a workspace shares its
25
+ root's. Workspace globs are read as npm reads them, a brace list expanded and a `!` entry leaving
26
+ a folder out, so a folder left out is a package root of its own, and so is a workspace that
27
+ declares workspaces of its own, since npm reads only one level of them.
28
+ - **No `.npmrc` sets any of the three otherwise.**
29
+ - **No file turns install scripts back on.** The flag given any value npm reads as false, such as
30
+ `false`, `0` or `null`, quoted or not, or written in its negated form, the
31
+ `npm_config_ignore_scripts` setting given anything but `true`, with `=` or `:`, in any case and
32
+ with a hyphen or an underscore before `scripts`, and an install pointed at another folder with
33
+ `--prefix` or `-C` without the flag that turns them off, are refused in a workflow's `env` block,
34
+ a `package.json` script, a hook, a shell script, a Dockerfile or any other text file the
35
+ repository tracks, apart from its docs and its tests.
36
+ - **Every Dockerfile stage sets `ENV npm_config_ignore_scripts=true` before its first RUN**,
37
+ whatever that RUN runs, since a script it calls may run npm, and before an `ONBUILD RUN` too. Only
38
+ ENV counts, since a build argument set with ARG can be given another value when the image is
39
+ built. A `FROM` an image starts a stage with the setting unset, and a `FROM` an earlier stage
40
+ inherits that stage's setting. An image build often copies only a `package.json` and its lockfile
41
+ before installing, so the `.npmrc` may not be there.
42
+
43
+ npm honors these settings for `npm ci`, `npm install`, npx and every other way of installing, so no
44
+ workflow, script or Dockerfile command needs to be read for how it installs. A flag that turns
45
+ install scripts off on an install stays harmless, and is no longer needed.
46
+
47
+ ## Lifecycle scripts under the rule
48
+
49
+ With install scripts off, npm skips more than a package's install scripts. It skips a repository's
50
+ own `prepare`, `prepack` and `prepublishOnly`, and every `pre` and `post` script, such as
51
+ `pretest`. npm's docs say a script run by name still runs: commands "explicitly intended to run a
52
+ particular script, such as `npm start`, `npm stop`, `npm restart`, `npm test`, and `npm run` will
53
+ still run their intended script if `ignore-scripts` is set". So under the rule:
54
+
55
+ - **Hooks are set up by name.** A hook manager such as husky sets itself up in `prepare`, so setup
56
+ runs it after installing:
57
+
58
+ ```sh
59
+ npm ci
60
+ npm run prepare
61
+ ```
62
+
63
+ - **A package builds by name before it packs.** A package that builds in `prepack` would be packed
64
+ without its build, so the build runs by name before `npm pack`, and `prepack` can go.
65
+ - **`allowScripts` can go.** The field lists packages allowed to run install scripts, and npm 11
66
+ does nothing with it by default.
67
+
68
+ A project's `.npmrc` covers the installs run in that project. An install pointed elsewhere reads the
69
+ other place's settings instead: a global install, such as `npm install -g`, or one given another
70
+ folder with `--prefix` or `-C`. So it carries the flag that turns install scripts off itself, and an
71
+ install given `--prefix` or `-C` without it is refused.
72
+
73
+ ## What it reads
74
+
75
+ - **Every `package.json`**, to find the package roots and the workspaces each lists, as an array or
76
+ under `packages`, with `*` for one folder's name and `**` for any depth.
77
+ - **Every `.npmrc`**, for its three settings at the top level, as npm's ini reader takes them: a
78
+ quoted value unquoted, an inline `;` or `#` comment left out, and a key written alone read as
79
+ true.
80
+ - **Dockerfiles**, any file named `Dockerfile`, `Dockerfile.` followed by a name, or ending in
81
+ `.Dockerfile`: each `FROM`, each `ENV` that sets `npm_config_ignore_scripts` in either form ENV
82
+ takes, and each `RUN` and `ONBUILD RUN`, with continued lines joined past comment and blank lines,
83
+ as Docker joins them, and a heredoc's body kept with its `RUN`.
84
+ - **Every other text file** the repository tracks, apart from its docs and its tests, for a line
85
+ that turns install scripts back on.
86
+
87
+ It reads every file git tracks and every new one git would add, leaving out what the repository
88
+ ignores.
89
+
90
+ ## Setup
91
+
92
+ ```sh
93
+ npm install --save-dev --save-exact @jasonsdevspace/repo-check
94
+ printf '\nignore-scripts=true\nallow-git=none\nallow-remote=none\n' >> .npmrc
95
+ ```
96
+
97
+ The settings are added to the `.npmrc` each package root already has, beside what it holds, after a
98
+ newline in case its last line has none. It
99
+ needs Node 24 or later and git. The install pins one exact version, since a minor version can fail
100
+ a build that passed, as [Versions and license](#versions-and-license) explains.
101
+
102
+ Run it in `verify`, beside the other checks, and in CI:
103
+
104
+ ```json
105
+ {
106
+ "scripts": {
107
+ "installs": "check-installs",
108
+ "verify": "npm run installs && npm run test:run"
109
+ }
110
+ }
111
+ ```
112
+
113
+ ## What a failure looks like
114
+
115
+ ```text
116
+ Install check failed. Each place below lets npm run install scripts:
117
+
118
+ demo/.npmrc is missing, and each package root holds one with the three settings
119
+ Dockerfile:9 runs before npm_config_ignore_scripts=true is set in its stage
120
+ npm ci --omit=dev
121
+ ```
122
+
123
+ Each problem names the file, and the line where there is one. The command exits 0 when the
124
+ repository keeps the rule, 1 when it does not, and 2 with how to run it when given an argument or
125
+ run outside a git repository.
126
+
127
+ ## What it exports
128
+
129
+ `installProblems(root)` returns every problem in the repository at `root`, in the form the command
130
+ prints, and an empty list when there are none. The rules it is built from are exported too:
131
+
132
+ - `packageRootsOf(manifests)` gives the package roots, by folder, from a map of each `package.json`
133
+ path to its text.
134
+ - `npmrcProblems(path, text, packageRoot)` gives what a `.npmrc` holds wrong.
135
+ - `dockerfileProblems(path, text)` gives each `RUN` that comes before its stage's setting.
136
+ - `scriptsOnProblems(path, text)` gives each line of a file that turns install scripts back on.
137
+ - `isDockerfile(path)` says whether a path names a Dockerfile, and `repositoryRoot(folder)` gives
138
+ the top of the git repository a folder sits in.
139
+
140
+ Each comes with its types.
141
+
142
+ ## Versions and license
143
+
144
+ The rules live in this package and nowhere else, so a repository takes a fix by moving its exact pin
145
+ to the version that holds it. The package is versioned on its own, and before 1.0.0 a version says
146
+ what a build may do once a repository moves to it:
147
+
148
+ - **A minor version** can fail a build that passed before: a rule that asks more than it did, or a
149
+ new command.
150
+ - **A patch** never fails a build that passed: a fix that stops a check from naming a file that
151
+ keeps its rule.
152
+
153
+ Read the
154
+ [changelog](https://github.com/jasonsdevspace/tooling/blob/main/packages/repo-check/CHANGELOG.md)
155
+ before moving to a minor version. The package is MIT licensed, and the terms are in
156
+ [LICENSE](https://github.com/jasonsdevspace/tooling/blob/main/packages/repo-check/LICENSE).
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Fails when the repository it is run in lets npm run install scripts or fetch git and URL
4
+ * dependencies: a package root whose `.npmrc` leaves out `ignore-scripts=true`, `allow-git=none` or
5
+ * `allow-remote=none`, a `.npmrc` that sets one otherwise, a file that turns install scripts back on,
6
+ * or a Dockerfile stage that runs before setting them off, naming each file, and passes otherwise.
7
+ * It exits 0 on a pass, 1 on a refusal, and 2 with how to run it when given an argument or run
8
+ * outside a git repository.
9
+ */
10
+ import { installProblems, repositoryRoot } from '../src/index.mjs';
11
+
12
+ if (process.argv.length > 2) {
13
+ console.error(
14
+ 'check-installs takes no arguments and reads the whole repository it is run in. Run it from anywhere inside the repository.'
15
+ );
16
+ process.exit(2);
17
+ }
18
+
19
+ /** @type {string[]} */
20
+ let failures;
21
+ try {
22
+ failures = installProblems(repositoryRoot(process.cwd()));
23
+ } catch (error) {
24
+ console.error(`check-installs: ${error instanceof Error ? error.message : String(error)}`);
25
+ process.exit(2);
26
+ }
27
+ if (failures.length > 0) {
28
+ console.error(`Install check failed. Each place below lets npm run install scripts:\n`);
29
+ console.error(failures.join('\n'));
30
+ process.exit(1);
31
+ }
32
+ console.log('Install check passed. npm runs no install scripts here.');
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
- "name": "@jasonsdevspace/repo-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@jasonsdevspace/repo-check",
3
+ "version": "0.1.0",
4
+ "description": "Fails a build wherever npm could run install scripts or fetch git or URL dependencies: a package root whose .npmrc lacks ignore-scripts=true, allow-git=none or allow-remote=none, a file that turns scripts back on, or an unset Dockerfile stage.",
5
+ "keywords": [
6
+ "npm",
7
+ "install-scripts",
8
+ "ignore-scripts",
9
+ "npmrc",
10
+ "dockerfile",
11
+ "supply-chain"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "Jason Poteet",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/jasonsdevspace/tooling.git",
18
+ "directory": "packages/repo-check"
19
+ },
20
+ "homepage": "https://github.com/jasonsdevspace/tooling/tree/main/packages/repo-check#readme",
21
+ "bugs": {
22
+ "url": "https://github.com/jasonsdevspace/tooling/issues"
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "engines": {
27
+ "node": ">=24"
28
+ },
29
+ "bin": {
30
+ "check-installs": "./bin/check-installs.mjs"
31
+ },
32
+ "exports": {
33
+ ".": {
34
+ "types": "./types/index.d.mts",
35
+ "default": "./src/index.mjs"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "bin",
41
+ "src/*.mjs",
42
+ "types"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "types": "tsc -p tsconfig.types.json"
49
+ }
50
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The repo check: `installProblems` for every place in a repository that lets npm run install
3
+ * scripts, which the `check-installs` command runs, and the rules it is built from.
4
+ */
5
+ export { installProblems, isDockerfile, repositoryRoot } from './repository.mjs';
6
+ export { dockerfileProblems, npmrcProblems, packageRootsOf, scriptsOnProblems } from './rules.mjs';
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The repo check over a whole repository: its package roots, its `.npmrc` files and its
3
+ * Dockerfiles.
4
+ */
5
+ import { execFileSync } from 'node:child_process';
6
+ import { readFileSync, statSync } from 'node:fs';
7
+ import { basename, join } from 'node:path';
8
+
9
+ import { dockerfileProblems, npmrcProblems, packageRootsOf, scriptsOnProblems } from './rules.mjs';
10
+
11
+ /**
12
+ * Whether a path names a Dockerfile: `Dockerfile`, `Dockerfile.` followed by a name, or a name
13
+ * ending in `.Dockerfile`. The prose check holds the same rule, and a test holds the two alike.
14
+ *
15
+ * @param {string} path
16
+ * @returns {boolean}
17
+ */
18
+ export function isDockerfile(path) {
19
+ return /^Dockerfile(\..+)?$|\.Dockerfile$/.test(basename(path));
20
+ }
21
+
22
+ /**
23
+ * The top of the git repository a folder sits in.
24
+ *
25
+ * @param {string} folder
26
+ * @returns {string}
27
+ */
28
+ export function repositoryRoot(folder) {
29
+ try {
30
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
31
+ cwd: folder,
32
+ encoding: 'utf8',
33
+ stdio: ['ignore', 'pipe', 'ignore'],
34
+ }).trim();
35
+ } catch {
36
+ throw new Error(`${folder} is not inside a git repository`);
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Whether a file is read for a line that turns install scripts back on: any text file but a doc, a
42
+ * test or a `.npmrc`, which has a rule of its own.
43
+ *
44
+ * @param {string} path
45
+ */
46
+ const readForScripts = (path) =>
47
+ !/\.(?:md|markdown|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|eot|pdf|zip|gz|tgz|wasm|mp4|webm|mov)$/i.test(
48
+ path
49
+ ) &&
50
+ !/(?:^|\/)(?:docs|tests?|__tests__)\//.test(path) &&
51
+ !/\.(?:test|spec)\.[^/]+$/.test(path) &&
52
+ !/(?:^|\/)\.npmrc$/.test(path);
53
+
54
+ /**
55
+ * Every place in the repository at `root` that lets npm run install scripts or fetch git and URL
56
+ * dependencies: a package root whose `.npmrc` leaves a setting out, a `.npmrc` that sets one
57
+ * otherwise, a Dockerfile stage that runs a command before turning install scripts off, and a line
58
+ * of any other text file but a doc or a test that turns them back on, each as `path:line what is wrong`, from the files git tracks
59
+ * and the new ones it would add.
60
+ *
61
+ * @param {string} root
62
+ * @returns {string[]}
63
+ */
64
+ export function installProblems(root) {
65
+ const listed = [
66
+ ...new Set(
67
+ execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
68
+ cwd: root,
69
+ encoding: 'utf8',
70
+ maxBuffer: 64 * 1024 * 1024,
71
+ }).split('\0')
72
+ ),
73
+ ].filter(
74
+ (path) => path !== '' && statSync(join(root, path), { throwIfNoEntry: false })?.isFile()
75
+ );
76
+ const read = (/** @type {string} */ path) => readFileSync(join(root, path), 'utf8');
77
+ const manifests = new Map(
78
+ listed
79
+ .filter((path) => path === 'package.json' || path.endsWith('/package.json'))
80
+ .map((path) => [path, read(path)])
81
+ );
82
+ const npmrcs = new Set(listed.filter((path) => path === '.npmrc' || path.endsWith('/.npmrc')));
83
+ const roots = new Set(
84
+ packageRootsOf(manifests).map((folder) => (folder === '' ? '.npmrc' : `${folder}/.npmrc`))
85
+ );
86
+ return [
87
+ ...[...roots]
88
+ .filter((path) => !npmrcs.has(path))
89
+ .map(
90
+ (path) =>
91
+ `${path} is missing, and each package root holds one with the three settings`
92
+ ),
93
+ ...[...npmrcs].flatMap((path) => npmrcProblems(path, read(path), roots.has(path))),
94
+ ...listed.filter(isDockerfile).flatMap((path) => dockerfileProblems(path, read(path))),
95
+ ...listed.filter(readForScripts).flatMap((path) => {
96
+ const text = read(path);
97
+ return text.includes('\0') ? [] : scriptsOnProblems(path, text);
98
+ }),
99
+ ];
100
+ }
package/src/rules.mjs ADDED
@@ -0,0 +1,392 @@
1
+ /**
2
+ * The rules the repo check holds: every package root turns npm's install scripts off in its
3
+ * `.npmrc` and keeps it from fetching git and URL dependencies, no file turns the scripts back on,
4
+ * and every Dockerfile stage turns them off before it runs anything. npm honors its own settings for
5
+ * every install however it is written, so how a workflow or a script installs need not be read.
6
+ */
7
+
8
+ /**
9
+ * A value as npm's ini reader takes it: quotes taken off a quoted value, and otherwise everything
10
+ * from an unescaped `;` or `#` on left out as a comment.
11
+ *
12
+ * @param {string} written
13
+ */
14
+ const iniValue = (written) => {
15
+ const quoted = /^(["'])(.*)\1$/.exec(written.trim());
16
+ if (quoted) return quoted[2] ?? '';
17
+ let value = '';
18
+ for (let at = 0; at < written.length; at += 1) {
19
+ const char = written[at] ?? '';
20
+ if (char === '\\' && at + 1 < written.length) {
21
+ value += written[at + 1] ?? '';
22
+ at += 1;
23
+ } else if (char === ';' || char === '#') break;
24
+ else value += char;
25
+ }
26
+ return value.trim();
27
+ };
28
+
29
+ /**
30
+ * Every line at the top level of an ini file, before any `[section]`, that sets a key, each with
31
+ * the value it gives and its line number. A key written alone is true, as npm reads it.
32
+ *
33
+ * @param {string} text
34
+ * @param {string} key
35
+ * @returns {{ value: string, line: number }[]}
36
+ */
37
+ const settingsOf = (text, key) => {
38
+ /** @type {{ value: string, line: number }[]} */
39
+ const settings = [];
40
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
41
+ for (const [index, line] of lines.entries()) {
42
+ if (/^\s*\[/.test(line)) break;
43
+ const found = /^\s*([^=;#\s][^=]*?)\s*(?:=(.*))?$/.exec(line);
44
+ if (!found || iniValue(found[1] ?? '') !== key) continue;
45
+ settings.push({
46
+ value: found[2] === undefined ? 'true' : iniValue(found[2]),
47
+ line: index + 1,
48
+ });
49
+ }
50
+ return settings;
51
+ };
52
+
53
+ /** The settings a package root's `.npmrc` holds, each with the value it needs and what any other does. */
54
+ const REQUIRED = [
55
+ { key: 'ignore-scripts', value: 'true', wrong: 'turns install scripts back on' },
56
+ { key: 'allow-git', value: 'none', wrong: 'lets npm fetch dependencies from git' },
57
+ { key: 'allow-remote', value: 'none', wrong: 'lets npm fetch dependencies from URLs' },
58
+ ];
59
+
60
+ /**
61
+ * What a `.npmrc` holds wrong: each line that sets one of the settings the check holds to another
62
+ * value than it needs, and, for a package root's own file, each of those settings it leaves out.
63
+ *
64
+ * @param {string} path
65
+ * @param {string} text
66
+ * @param {boolean} packageRoot
67
+ * @returns {string[]}
68
+ */
69
+ export function npmrcProblems(path, text, packageRoot) {
70
+ return REQUIRED.flatMap(({ key, value: needed, wrong }) => {
71
+ const settings = settingsOf(text, key);
72
+ const problems = settings
73
+ .filter(({ value }) => value !== needed)
74
+ .map(({ value, line }) => `${path}:${line} ${key}=${value} ${wrong}`);
75
+ if (packageRoot && !settings.some(({ value }) => value === needed))
76
+ problems.unshift(
77
+ `${path} a package root's .npmrc sets ${key}=${needed}, and this one does not`
78
+ );
79
+ return problems;
80
+ });
81
+ }
82
+
83
+ /**
84
+ * A glob with each brace list expanded, `{a,b}/*` as `a/*` and `b/*`.
85
+ *
86
+ * @param {string} glob
87
+ * @returns {string[]}
88
+ */
89
+ const expanded = (glob) => {
90
+ const found = /\{([^{}]*)\}/.exec(glob);
91
+ if (!found) return [glob];
92
+ const [whole, list = ''] = found;
93
+ return list
94
+ .split(',')
95
+ .flatMap((choice) =>
96
+ expanded(glob.slice(0, found.index) + choice + glob.slice(found.index + whole.length))
97
+ );
98
+ };
99
+
100
+ /**
101
+ * The pattern a workspace glob names, from the folder of the package.json that lists it: `**` for
102
+ * any depth and `*` for one folder's name.
103
+ *
104
+ * @param {string} folder
105
+ * @param {string} glob
106
+ */
107
+ const workspacePattern = (folder, glob) => {
108
+ const path = `${folder === '' ? '' : `${folder}/`}${glob.replace(/^\.\//, '').replace(/\/+$/, '')}`;
109
+ const source = path
110
+ .split('/')
111
+ .map((part) =>
112
+ part === '**'
113
+ ? '.*'
114
+ : part.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')
115
+ )
116
+ .join('/');
117
+ return new RegExp(`^${source}$`);
118
+ };
119
+
120
+ /**
121
+ * The workspace globs a package.json lists, as an array or under `packages`, or none.
122
+ *
123
+ * @param {string} text
124
+ * @returns {string[]}
125
+ */
126
+ const workspacesOf = (text) => {
127
+ /** @type {unknown} */
128
+ let manifest;
129
+ try {
130
+ manifest = JSON.parse(text);
131
+ } catch {
132
+ return [];
133
+ }
134
+ if (typeof manifest !== 'object' || manifest === null || !('workspaces' in manifest)) return [];
135
+ /** @type {unknown} */
136
+ const listed = manifest.workspaces;
137
+ /** @type {unknown} */
138
+ const globs =
139
+ typeof listed === 'object' && listed !== null && 'packages' in listed
140
+ ? listed.packages
141
+ : listed;
142
+ return Array.isArray(globs) ? globs.filter((glob) => typeof glob === 'string') : [];
143
+ };
144
+
145
+ /**
146
+ * The folders that are package roots, from the package.json files a repository holds, each by its
147
+ * folder: the repository's root, and each folder with a package.json of its own that no package
148
+ * above it lists as a workspace, since a workspace shares its root's `.npmrc`. As npm reads the
149
+ * globs, a brace list is expanded and a `!` entry leaves out what the others matched, so a folder it
150
+ * leaves out is a package root of its own.
151
+ *
152
+ * @param {ReadonlyMap<string, string>} manifests
153
+ * @returns {string[]}
154
+ */
155
+ export function packageRootsOf(manifests) {
156
+ const folders = [...manifests.keys()]
157
+ .map((path) => (path === 'package.json' ? '' : path.slice(0, -'/package.json'.length)))
158
+ .sort((a, b) => b.length - a.length);
159
+ const lists = new Map(
160
+ folders.map((folder) => {
161
+ const globs = workspacesOf(
162
+ manifests.get(folder === '' ? 'package.json' : `${folder}/package.json`) ?? ''
163
+ ).flatMap(expanded);
164
+ const pattern = (/** @type {string} */ glob) => workspacePattern(folder, glob);
165
+ return [
166
+ folder,
167
+ {
168
+ declares: globs.length > 0,
169
+ included: globs.filter((glob) => !glob.startsWith('!')).map(pattern),
170
+ excluded: globs
171
+ .filter((glob) => glob.startsWith('!'))
172
+ .map((glob) => pattern(glob.slice(1))),
173
+ },
174
+ ];
175
+ })
176
+ );
177
+ const above = (/** @type {string} */ folder) =>
178
+ folders.filter(
179
+ (other) => other !== folder && (other === '' || folder.startsWith(`${other}/`))
180
+ );
181
+ // A folder is a workspace of the nearest package above it whose globs list it, unless that
182
+ // package's `!` entries leave it out. One that declares workspaces of its own is a package root,
183
+ // since npm reads only one level of workspaces, from the root it runs in.
184
+ const isWorkspace = (/** @type {string} */ folder) => {
185
+ for (const other of above(folder)) {
186
+ const list = lists.get(other);
187
+ if (list?.included.some((pattern) => pattern.test(folder)))
188
+ return !list.excluded.some((pattern) => pattern.test(folder));
189
+ }
190
+ return false;
191
+ };
192
+ return folders
193
+ .filter(
194
+ (folder) =>
195
+ folder === '' || lists.get(folder)?.declares === true || !isWorkspace(folder)
196
+ )
197
+ .sort((a, b) => a.length - b.length);
198
+ }
199
+
200
+ /**
201
+ * Whether an ENV instruction's words turn npm's install scripts off, on, or leave them as they
202
+ * were: `true`, `false` or undefined.
203
+ *
204
+ * @param {string} rest
205
+ * @returns {boolean | undefined}
206
+ */
207
+ const scriptsSetting = (rest) => {
208
+ const pairs = [...rest.matchAll(/(\S+?)=("[^"]*"|'[^']*'|\S*)/g)].map(
209
+ ([, key = '', value = '']) => [key, value.replace(/^(["'])(.*)\1$/, '$2')]
210
+ );
211
+ const legacy = /^(\S+)\s+(\S.*)$/.exec(rest.trim());
212
+ const all = pairs.length > 0 ? pairs : legacy ? [[legacy[1] ?? '', legacy[2] ?? '']] : [];
213
+ /** @type {boolean | undefined} */
214
+ let setting;
215
+ for (const [key = '', value = ''] of all) {
216
+ if (SETTING_NAME.test(key)) setting = value.trim() === 'true';
217
+ }
218
+ return setting;
219
+ };
220
+
221
+ /**
222
+ * Each instruction of a Dockerfile with the line it starts on: continued lines joined past any
223
+ * comment or blank line among them, as Docker joins them, comment lines dropped, and a heredoc's body kept
224
+ * with the RUN that opens it.
225
+ *
226
+ * @param {string} text
227
+ * @returns {{ text: string, line: number }[]}
228
+ */
229
+ const instructionsOf = (text) => {
230
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
231
+ /** @type {{ text: string, line: number }[]} */
232
+ const instructions = [];
233
+ let at = 0;
234
+ while (at < lines.length) {
235
+ const start = at;
236
+ let joined = lines[at] ?? '';
237
+ at += 1;
238
+ if (/^\s*#/.test(joined) || joined.trim() === '') continue;
239
+ while (/\\[ \t]*$/.test(joined) && at < lines.length) {
240
+ const next = lines[at] ?? '';
241
+ at += 1;
242
+ joined = joined.replace(/\\[ \t]*$/, '\\');
243
+ if (!/^\s*#/.test(next) && next.trim() !== '')
244
+ joined = `${joined.slice(0, -1)} ${next}`;
245
+ }
246
+ const heredoc = /(?:^|\s)<<-?(["']?)([A-Za-z_]\w*)\1/.exec(joined);
247
+ const end = heredoc
248
+ ? lines.findIndex((line, index) => index >= at && line.trim() === heredoc[2])
249
+ : -1;
250
+ if (end >= 0) {
251
+ joined = `${joined}\n${lines.slice(at, end).join('\n')}`;
252
+ at = end + 1;
253
+ }
254
+ instructions.push({ text: joined, line: start + 1 });
255
+ }
256
+ return instructions;
257
+ };
258
+
259
+ /**
260
+ * The stage a FROM starts: the image or earlier stage it builds on, and the name it gives itself.
261
+ *
262
+ * @param {string} rest
263
+ */
264
+ const stageOf = (rest) => {
265
+ const words = rest.split(/\s+/).filter((word) => word !== '' && !word.startsWith('--'));
266
+ const as = words.findIndex((word) => word.toLowerCase() === 'as');
267
+ return { base: words[0] ?? '', name: as >= 0 ? words[as + 1] : undefined };
268
+ };
269
+
270
+ /**
271
+ * The setting a FROM's stage starts with, and the name it is known by: an earlier stage's setting
272
+ * when it builds on one, and unset when it builds on an image.
273
+ *
274
+ * @param {string} rest
275
+ * @param {ReadonlyMap<string, boolean>} stages
276
+ */
277
+ const entering = (rest, stages) => {
278
+ const { base, name } = stageOf(rest);
279
+ return { off: stages.get(base.toLowerCase()) ?? false, stage: name?.toLowerCase() };
280
+ };
281
+
282
+ /**
283
+ * Whether an instruction runs a command in the image, as RUN does now and ONBUILD RUN does in a
284
+ * later build.
285
+ *
286
+ * @param {string} keyword
287
+ * @param {string} rest
288
+ */
289
+ const runs = (keyword, rest) =>
290
+ keyword === 'RUN' || (keyword === 'ONBUILD' && /^RUN\b/i.test(rest));
291
+
292
+ /**
293
+ * Each RUN of a Dockerfile, ONBUILD RUN among them, that comes before its stage sets the npm setting
294
+ * that turns install scripts off to true with ENV, whatever it runs, since a script it calls may run
295
+ * npm. ARG does not count, since a build argument can be set otherwise when the image is built. A
296
+ * FROM starts a stage with the setting unset, unless it builds on an earlier stage, whose setting it
297
+ * inherits.
298
+ *
299
+ * @param {string} path
300
+ * @param {string} text
301
+ * @returns {string[]}
302
+ */
303
+ export function dockerfileProblems(path, text) {
304
+ /** @type {string[]} */
305
+ const problems = [];
306
+ /** @type {Map<string, boolean>} */
307
+ const stages = new Map();
308
+ /** @type {string | undefined} */
309
+ let stage;
310
+ let off = false;
311
+ for (const { text: instruction, line } of instructionsOf(text)) {
312
+ const [, word = '', rest = ''] = /^\s*(\S+)\s*([\s\S]*)$/.exec(instruction) ?? [];
313
+ const keyword = word.toUpperCase();
314
+ if (keyword === 'FROM') {
315
+ if (stage !== undefined) stages.set(stage, off);
316
+ ({ off, stage } = entering(rest, stages));
317
+ } else if (keyword === 'ENV') off = scriptsSetting(rest) ?? off;
318
+ else if (runs(keyword, rest) && !off)
319
+ problems.push(
320
+ `${path}:${line} runs before ${SETTING}=true is set in its stage\n ${rest.split('\n')[0]?.trim() ?? ''}`
321
+ );
322
+ }
323
+ return problems;
324
+ }
325
+
326
+ /**
327
+ * The npm flag and environment setting that name install scripts, each built from its parts, so
328
+ * this file holds neither whole and the check can read it like any other. npm reads the setting's
329
+ * name in any case, with an underscore or a hyphen after the prefix.
330
+ */
331
+ const FLAG = ['--ignore', '-scripts'].join('');
332
+ const SETTING = ['npm_config', '_ignore', '_scripts'].join('');
333
+ const SETTING_SOURCE = `${SETTING.slice(0, -'_scripts'.length)}[-_]scripts`;
334
+ const SETTING_NAME = new RegExp(`^${SETTING_SOURCE}$`, 'i');
335
+
336
+ /** A value with its quotes taken off, in lower case. */
337
+ const plain = (/** @type {string} */ value) => value.replace(/^(["'])(.*)\1$/, '$2').toLowerCase();
338
+
339
+ /**
340
+ * The flag given a value with `=`, which npm reads as false for anything but true, and the flag
341
+ * followed by a word npm reads as false, quoted or not.
342
+ */
343
+ const FLAG_VALUE = new RegExp(`${FLAG}=("[^"]*"|'[^']*'|[^\\s;&|)]*)`, 'gi');
344
+ const FLAG_FALSE = new RegExp(
345
+ `${FLAG}\\s+(["']?)(?:false|0|null)\\1(?![\\w-])|--no${FLAG.slice(1)}\\b`,
346
+ 'i'
347
+ );
348
+
349
+ /**
350
+ * The environment setting given a value with `=` or `:`, quoted or not, in any case. An unquoted
351
+ * value ends at a space, a shell operator, a bracket, a backslash, a backtick or a quote.
352
+ */
353
+ const SETTING_VALUE = new RegExp(
354
+ `${SETTING_SOURCE}["']?\\s*[:=]\\s*("[^"\\n]*"|'[^'\\n]*'|[^\\s;&|,})\\]\\\\\\x60"']*)`,
355
+ 'gi'
356
+ );
357
+
358
+ /** npm's subcommands that install, in every spelling it accepts. */
359
+ const INSTALLS =
360
+ 'ci|clean-install|ic|install-clean|isntall-clean|i|in|ins|inst|insta|instal|install|isnt|isnta|isntal|isntall|add|it|cit|sit|install-test|install-ci-test|clean-install-test|rebuild|rb|update|up|upgrade|udpate|dedupe|ddp|link|ln';
361
+
362
+ /** An npm install on a line that names another project with `--prefix` or `-C`. */
363
+ const INSTALL = new RegExp(`(?:^|[\\s;&|(])npm\\s(?:.*\\s)?(?:${INSTALLS})(?=\\s|$)`);
364
+ const ELSEWHERE = /\s(?:--prefix(?:=|\s)|-C\s)/;
365
+ const FLAG_OFF = new RegExp(`${FLAG}(?![=\\w-])|${FLAG}=(["']?)true\\1(?![\\w-])`, 'i');
366
+
367
+ /**
368
+ * Each line of a file that turns install scripts back on: the flag given any value npm reads as
369
+ * false or negated, the environment setting given any value but true, or an install pointed at
370
+ * another project with `--prefix` or `-C`, which reads that project's settings rather than this
371
+ * one's, without the flag that turns them off.
372
+ *
373
+ * @param {string} path
374
+ * @param {string} text
375
+ * @returns {string[]}
376
+ */
377
+ export function scriptsOnProblems(path, text) {
378
+ return text
379
+ .replace(/\r\n/g, '\n')
380
+ .split('\n')
381
+ .flatMap((line, index) => {
382
+ const flagOn =
383
+ FLAG_FALSE.test(line) ||
384
+ [...line.matchAll(FLAG_VALUE)].some(([, value = '']) => plain(value) !== 'true');
385
+ const setOn = [...line.matchAll(SETTING_VALUE)].some(
386
+ ([, value = '']) => plain(value) !== 'true'
387
+ );
388
+ const elsewhere = INSTALL.test(line) && ELSEWHERE.test(line) && !FLAG_OFF.test(line);
389
+ if (!flagOn && !setOn && !elsewhere) return [];
390
+ return [`${path}:${index + 1} turns install scripts back on\n ${line.trim()}`];
391
+ });
392
+ }
@@ -0,0 +1,2 @@
1
+ export { installProblems, isDockerfile, repositoryRoot } from "./repository.mjs";
2
+ export { dockerfileProblems, npmrcProblems, packageRootsOf, scriptsOnProblems } from "./rules.mjs";
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Whether a path names a Dockerfile: `Dockerfile`, `Dockerfile.` followed by a name, or a name
3
+ * ending in `.Dockerfile`. The prose check holds the same rule, and a test holds the two alike.
4
+ *
5
+ * @param {string} path
6
+ * @returns {boolean}
7
+ */
8
+ export function isDockerfile(path: string): boolean;
9
+ /**
10
+ * The top of the git repository a folder sits in.
11
+ *
12
+ * @param {string} folder
13
+ * @returns {string}
14
+ */
15
+ export function repositoryRoot(folder: string): string;
16
+ /**
17
+ * Every place in the repository at `root` that lets npm run install scripts or fetch git and URL
18
+ * dependencies: a package root whose `.npmrc` leaves a setting out, a `.npmrc` that sets one
19
+ * otherwise, a Dockerfile stage that runs a command before turning install scripts off, and a line
20
+ * of any other text file but a doc or a test that turns them back on, each as `path:line what is wrong`, from the files git tracks
21
+ * and the new ones it would add.
22
+ *
23
+ * @param {string} root
24
+ * @returns {string[]}
25
+ */
26
+ export function installProblems(root: string): string[];
@@ -0,0 +1,44 @@
1
+ /**
2
+ * What a `.npmrc` holds wrong: each line that sets one of the settings the check holds to another
3
+ * value than it needs, and, for a package root's own file, each of those settings it leaves out.
4
+ *
5
+ * @param {string} path
6
+ * @param {string} text
7
+ * @param {boolean} packageRoot
8
+ * @returns {string[]}
9
+ */
10
+ export function npmrcProblems(path: string, text: string, packageRoot: boolean): string[];
11
+ /**
12
+ * The folders that are package roots, from the package.json files a repository holds, each by its
13
+ * folder: the repository's root, and each folder with a package.json of its own that no package
14
+ * above it lists as a workspace, since a workspace shares its root's `.npmrc`. As npm reads the
15
+ * globs, a brace list is expanded and a `!` entry leaves out what the others matched, so a folder it
16
+ * leaves out is a package root of its own.
17
+ *
18
+ * @param {ReadonlyMap<string, string>} manifests
19
+ * @returns {string[]}
20
+ */
21
+ export function packageRootsOf(manifests: ReadonlyMap<string, string>): string[];
22
+ /**
23
+ * Each RUN of a Dockerfile, ONBUILD RUN among them, that comes before its stage sets the npm setting
24
+ * that turns install scripts off to true with ENV, whatever it runs, since a script it calls may run
25
+ * npm. ARG does not count, since a build argument can be set otherwise when the image is built. A
26
+ * FROM starts a stage with the setting unset, unless it builds on an earlier stage, whose setting it
27
+ * inherits.
28
+ *
29
+ * @param {string} path
30
+ * @param {string} text
31
+ * @returns {string[]}
32
+ */
33
+ export function dockerfileProblems(path: string, text: string): string[];
34
+ /**
35
+ * Each line of a file that turns install scripts back on: the flag given any value npm reads as
36
+ * false or negated, the environment setting given any value but true, or an install pointed at
37
+ * another project with `--prefix` or `-C`, which reads that project's settings rather than this
38
+ * one's, without the flag that turns them off.
39
+ *
40
+ * @param {string} path
41
+ * @param {string} text
42
+ * @returns {string[]}
43
+ */
44
+ export function scriptsOnProblems(path: string, text: string): string[];