@jasonsdevspace/repo-check 0.0.0-stage → 0.2.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,199 @@
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 sets them otherwise.** npm reads a command's flags and the `npm_config_` environment
30
+ settings ahead of a project's `.npmrc`, so each is refused where it gives another value, in a
31
+ workflow's `env` block, a `package.json` script, a hook, a shell script, a Dockerfile or any other
32
+ text file the repository tracks, apart from its docs and its tests:
33
+ - the install scripts flag given any value npm reads as false, such as `false`, `0` or `null`,
34
+ quoted or not, or written in its negated form
35
+ - the `npm_config_ignore_scripts` setting given anything but `true`
36
+ - the `--allow-git` and `--allow-remote` flags, and the `npm_config_allow_git` and
37
+ `npm_config_allow_remote` settings, given anything but `none`
38
+
39
+ A setting is read with `=` or `:`, in any case, with a hyphen or an underscore between its
40
+ words, and after a quote and a closing bracket where code reads it as a key, such as
41
+ `process.env["npm_config_ignore_scripts"] = "false"`.
42
+
43
+ - **No command rewrites the project's `.npmrc`.** npm's config command run with `--location=project`
44
+ or `-L project`, to set or delete one of the three settings, or to edit the file, is refused,
45
+ since it would change the file after the check has read it.
46
+ - **No install leaves the project without its settings.** An install pointed at another folder with
47
+ `--prefix` or `-C`, or at npm's global folder with `-g`, `--global` or `--location=global`, reads
48
+ another project's settings rather than this one's, so it is refused unless it passes the flag that
49
+ turns install scripts off, and `--allow-git=none` with `--allow-remote=none`, or `--offline`,
50
+ which fetches nothing. The check reads the line, not the environment it runs in, so the flags are
51
+ needed even where an `npm_config_` setting already holds them. Each command on a line is judged by
52
+ its own words.
53
+ - **No command fetches a tool to run it.** npx, and npm's `exec` command and its alias `x`, fetch a
54
+ tool that is not installed, and run it, unless told not to, so each is refused unless its own
55
+ options end with `--no`, or with `--no-install` for npx, which reads it as `--no`. npm's `exec`
56
+ command does not, so there `--no-install` stops nothing. npm's `create` command, and its `init`
57
+ command given an initializer, always fetch one, so each is refused. A command is read where it
58
+ starts a line, a script or a step, so a sentence that names one is passed over.
59
+ - **Every Dockerfile stage holds all three settings before its first RUN**, whatever that RUN runs,
60
+ since a script it calls may run npm, and before an `ONBUILD RUN` too. A stage holds them when it
61
+ sets `npm_config_ignore_scripts=true`, `npm_config_allow_git=none` and
62
+ `npm_config_allow_remote=none` with ENV, or copies in the `.npmrc` by name, into the folder its
63
+ `WORKDIR` names. An image build often copies only a `package.json` and its lockfile before
64
+ installing, so the repository's `.npmrc` counts only where the stage copies it there, and a copy
65
+ of a whole folder does not count, since a `.dockerignore` may leave the file out. Only ENV counts
66
+ among the instructions that set, since a build argument set with ARG can be given another value
67
+ when the image is built. A `FROM` an image starts a stage with nothing set, and a `FROM` an
68
+ earlier stage inherits what that stage held.
69
+ - **The npm that runs the check is 11.14.0 or later**, the first that reads `allow-git` and
70
+ `allow-remote`. An older npm, or a prerelease of 11.14.0, passes over both without a word. The
71
+ command reads the version from the user agent npm sets for a script it runs, and otherwise asks
72
+ the npm on the path. The floor is held by the command
73
+ rather than by `engines.npm`, since Dependabot's npm updater reads that field and may refuse to
74
+ run on an older npm.
75
+
76
+ npm honors these settings for `npm ci`, `npm install` and every other way of installing inside the
77
+ project, so no command needs to be read for how it installs, apart from the two cases no project
78
+ setting reaches, an install outside the project and a tool fetched to run. A flag that turns
79
+ install scripts off on an install inside the project stays harmless, and is no longer needed.
80
+
81
+ ## Lifecycle scripts under the rule
82
+
83
+ With install scripts off, npm skips more than a package's install scripts. It skips a repository's
84
+ own `prepare`, `prepack` and `prepublishOnly`, and every `pre` and `post` script, such as
85
+ `pretest`. npm's docs say a script run by name still runs: commands "explicitly intended to run a
86
+ particular script, such as `npm start`, `npm stop`, `npm restart`, `npm test`, and `npm run` will
87
+ still run their intended script if `ignore-scripts` is set". So under the rule:
88
+
89
+ - **Hooks are set up by name.** A hook manager such as husky sets itself up in `prepare`, so setup
90
+ runs it after installing:
91
+
92
+ ```sh
93
+ npm ci
94
+ npm run prepare
95
+ ```
96
+
97
+ - **A package builds by name before it packs.** A package that builds in `prepack` would be packed
98
+ without its build, so the build runs by name before `npm pack`, and `prepack` can go.
99
+ - **`allowScripts` can go.** The field lists packages allowed to run install scripts, and npm 11
100
+ does nothing with it by default.
101
+
102
+ A project's `.npmrc` covers the installs run in that project. An install pointed elsewhere reads the
103
+ other place's settings instead: a global install, such as `npm install -g`, or one given another
104
+ folder with `--prefix` or `-C`. So it carries the flag that turns install scripts off itself, and an
105
+ install given `--prefix` or `-C` without it is refused.
106
+
107
+ ## What it reads
108
+
109
+ - **Every `package.json`**, to find the package roots and the workspaces each lists, as an array or
110
+ under `packages`, with `*` for one folder's name and `**` for any depth.
111
+ - **Every `.npmrc`**, for its three settings at the top level, as npm's ini reader takes them: a
112
+ quoted value unquoted, an inline `;` or `#` comment left out, and a key written alone read as
113
+ true.
114
+ - **Dockerfiles**, any file named `Dockerfile`, `Dockerfile.` followed by a name, or ending in
115
+ `.Dockerfile`: each `FROM`, each `ENV` that sets one of the three settings in either form ENV
116
+ takes, each `WORKDIR`, each `COPY` and `ADD` that names a `.npmrc`, and each `RUN` and `ONBUILD
117
+ RUN`, with continued lines joined past comment and blank lines, as Docker joins them, and a
118
+ heredoc's body kept with its `RUN`.
119
+ - **Every other text file** the repository tracks, apart from its docs and its tests, a line at a
120
+ time, for a setting given another value, a write to the project's `.npmrc`, an install outside the
121
+ project and a tool fetched to run.
122
+ - **The npm on the path**, for its version.
123
+
124
+ It reads every file git tracks and every new one git would add, leaving out what the repository
125
+ ignores.
126
+
127
+ ## Setup
128
+
129
+ ```sh
130
+ npm install --save-dev --save-exact @jasonsdevspace/repo-check
131
+ printf '\nignore-scripts=true\nallow-git=none\nallow-remote=none\n' >> .npmrc
132
+ ```
133
+
134
+ The settings are added to the `.npmrc` each package root already has, beside what it holds, after a
135
+ newline in case its last line has none. It needs Node 24.18 or later, the first whose bundled npm is
136
+ 11.14.0 or later, and git. The install pins one exact version, since a minor version can fail a
137
+ build that passed, as [Versions and license](#versions-and-license) explains.
138
+
139
+ Run it in `verify`, beside the other checks, and in CI:
140
+
141
+ ```json
142
+ {
143
+ "scripts": {
144
+ "installs": "check-installs",
145
+ "verify": "npm run installs && npm run test:run"
146
+ }
147
+ }
148
+ ```
149
+
150
+ ## What a failure looks like
151
+
152
+ ```text
153
+ Install check failed. Each place below lets npm run install scripts or fetch what it should not:
154
+
155
+ demo/.npmrc is missing, and each package root holds one with the three settings
156
+ Dockerfile:9 runs before its stage sets npm_config_ignore_scripts=true with ENV or copies in the .npmrc
157
+ npm ci --omit=dev
158
+ .github/workflows/ci.yml:31 may fetch a package to run it, without --no, or --no-install for npx, to stop it
159
+ - run: npx playwright install --with-deps
160
+ ```
161
+
162
+ Each problem names the file, and the line where there is one. The command exits 0 when the
163
+ repository keeps the rule, 1 when it does not, and 2 with how to run it when given an argument or
164
+ run outside a git repository.
165
+
166
+ ## What it exports
167
+
168
+ `installProblems(root)` returns every problem in the repository at `root`, in the form the command
169
+ prints, and an empty list when there are none. The rules it is built from are exported too:
170
+
171
+ - `packageRootsOf(manifests)` gives the package roots, by folder, from a map of each `package.json`
172
+ path to its text.
173
+ - `npmrcProblems(path, text, packageRoot)` gives what a `.npmrc` holds wrong.
174
+ - `dockerfileProblems(path, text)` gives each `RUN` that comes before its stage holds the settings.
175
+ - `scriptsOnProblems(path, text)` gives each line of a file that sets one of the settings
176
+ otherwise, rewrites the project's `.npmrc`, installs outside the project with install scripts on,
177
+ or fetches a tool to run it.
178
+ - `npmFloorProblems(version)` gives what is wrong with an npm of that version, an empty list for
179
+ 11.14.0 or later.
180
+ - `isDockerfile(path)` says whether a path names a Dockerfile, and `repositoryRoot(folder)` gives
181
+ the top of the git repository a folder sits in.
182
+
183
+ Each comes with its types.
184
+
185
+ ## Versions and license
186
+
187
+ The rules live in this package and nowhere else, so a repository takes a fix by moving its exact pin
188
+ to the version that holds it. The package is versioned on its own, and before 1.0.0 a version says
189
+ what a build may do once a repository moves to it:
190
+
191
+ - **A minor version** can fail a build that passed before: a rule that asks more than it did, or a
192
+ new command.
193
+ - **A patch** never fails a build that passed: a fix that stops a check from naming a file that
194
+ keeps its rule.
195
+
196
+ Read the
197
+ [changelog](https://github.com/jasonsdevspace/tooling/blob/main/packages/repo-check/CHANGELOG.md)
198
+ before moving to a minor version. The package is MIT licensed, and the terms are in
199
+ [LICENSE](https://github.com/jasonsdevspace/tooling/blob/main/packages/repo-check/LICENSE).
@@ -0,0 +1,48 @@
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`, flag or setting that gives one another value, a Dockerfile stage
6
+ * that runs before holding all three, an install outside the project with install scripts on, or a
7
+ * tool fetched to run, naming each file, and when the npm running it is too old to read the
8
+ * settings. It passes otherwise.
9
+ * It exits 0 on a pass, 1 on a refusal, and 2 with how to run it when given an argument or run
10
+ * outside a git repository.
11
+ */
12
+ import { execFileSync } from 'node:child_process';
13
+
14
+ import { installProblems, npmFloorProblems, repositoryRoot } from '../src/index.mjs';
15
+
16
+ if (process.argv.length > 2) {
17
+ console.error(
18
+ 'check-installs takes no arguments and reads the whole repository it is run in. Run it from anywhere inside the repository.'
19
+ );
20
+ process.exit(2);
21
+ }
22
+
23
+ /** @type {string[]} */
24
+ let failures;
25
+ try {
26
+ // npm names itself in the user agent it sets for a script it runs, which is the npm that reads
27
+ // the settings. Run another way, the npm on the path is asked, through a shell on Windows, where
28
+ // npm is a script that cannot be run without one.
29
+ const agent = /(?:^|\s)npm\/(\S+)/.exec(process.env['npm_config_user_agent'] ?? '')?.[1];
30
+ const npm =
31
+ agent ??
32
+ execFileSync('npm', ['--version'], {
33
+ encoding: 'utf8',
34
+ shell: process.platform === 'win32',
35
+ });
36
+ failures = [...npmFloorProblems(npm), ...installProblems(repositoryRoot(process.cwd()))];
37
+ } catch (error) {
38
+ console.error(`check-installs: ${error instanceof Error ? error.message : String(error)}`);
39
+ process.exit(2);
40
+ }
41
+ if (failures.length > 0) {
42
+ console.error(
43
+ `Install check failed. Each place below lets npm run install scripts or fetch what it should not:\n`
44
+ );
45
+ console.error(failures.join('\n'));
46
+ process.exit(1);
47
+ }
48
+ 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.2.0",
4
+ "description": "Fails a build wherever npm could run install scripts or fetch git or URL dependencies: a package root whose .npmrc lacks the settings that stop them, a flag, setting or command that gives one another value, an unset Dockerfile stage, an install outside the project, or a tool fetched to run.",
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.18"
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,12 @@
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 {
7
+ dockerfileProblems,
8
+ npmFloorProblems,
9
+ npmrcProblems,
10
+ packageRootsOf,
11
+ scriptsOnProblems,
12
+ } 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,727 @@
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 sets any of those settings
4
+ * otherwise, and every Dockerfile stage sets all three before it runs anything. npm honors its own
5
+ * settings for every install however it is written, so how an install is written need not be read,
6
+ * apart from the two cases no project setting reaches: an install into npm's global folder, and a
7
+ * tool that npx, or npm's exec command, may fetch to run.
8
+ */
9
+
10
+ /**
11
+ * A value as npm's ini reader takes it: quotes taken off a quoted value, and otherwise everything
12
+ * from an unescaped `;` or `#` on left out as a comment.
13
+ *
14
+ * @param {string} written
15
+ */
16
+ const iniValue = (written) => {
17
+ const quoted = /^(["'])(.*)\1$/.exec(written.trim());
18
+ if (quoted) return quoted[2] ?? '';
19
+ let value = '';
20
+ for (let at = 0; at < written.length; at += 1) {
21
+ const char = written[at] ?? '';
22
+ if (char === '\\' && at + 1 < written.length) {
23
+ value += written[at + 1] ?? '';
24
+ at += 1;
25
+ } else if (char === ';' || char === '#') break;
26
+ else value += char;
27
+ }
28
+ return value.trim();
29
+ };
30
+
31
+ /**
32
+ * Every line at the top level of an ini file, before any `[section]`, that sets a key, each with
33
+ * the value it gives and its line number. A key written alone is true, as npm reads it.
34
+ *
35
+ * @param {string} text
36
+ * @param {string} key
37
+ * @returns {{ value: string, line: number }[]}
38
+ */
39
+ const settingsOf = (text, key) => {
40
+ /** @type {{ value: string, line: number }[]} */
41
+ const settings = [];
42
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
43
+ for (const [index, line] of lines.entries()) {
44
+ if (/^\s*\[/.test(line)) break;
45
+ const found = /^\s*([^=;#\s][^=]*?)\s*(?:=(.*))?$/.exec(line);
46
+ if (!found || iniValue(found[1] ?? '') !== key) continue;
47
+ settings.push({
48
+ value: found[2] === undefined ? 'true' : iniValue(found[2]),
49
+ line: index + 1,
50
+ });
51
+ }
52
+ return settings;
53
+ };
54
+
55
+ /** The settings a package root's `.npmrc` holds, each with the value it needs and what any other does. */
56
+ const REQUIRED = [
57
+ { key: 'ignore-scripts', value: 'true', wrong: 'turns install scripts back on' },
58
+ { key: 'allow-git', value: 'none', wrong: 'lets npm fetch dependencies from git' },
59
+ { key: 'allow-remote', value: 'none', wrong: 'lets npm fetch dependencies from URLs' },
60
+ ];
61
+
62
+ /**
63
+ * What a `.npmrc` holds wrong: each line that sets one of the settings the check holds to another
64
+ * value than it needs, and, for a package root's own file, each of those settings it leaves out.
65
+ *
66
+ * @param {string} path
67
+ * @param {string} text
68
+ * @param {boolean} packageRoot
69
+ * @returns {string[]}
70
+ */
71
+ export function npmrcProblems(path, text, packageRoot) {
72
+ return REQUIRED.flatMap(({ key, value: needed, wrong }) => {
73
+ const settings = settingsOf(text, key);
74
+ const problems = settings
75
+ .filter(({ value }) => value !== needed)
76
+ .map(({ value, line }) => `${path}:${line} ${key}=${value} ${wrong}`);
77
+ if (packageRoot && !settings.some(({ value }) => value === needed))
78
+ problems.unshift(
79
+ `${path} a package root's .npmrc sets ${key}=${needed}, and this one does not`
80
+ );
81
+ return problems;
82
+ });
83
+ }
84
+
85
+ /**
86
+ * A glob with each brace list expanded, `{a,b}/*` as `a/*` and `b/*`.
87
+ *
88
+ * @param {string} glob
89
+ * @returns {string[]}
90
+ */
91
+ const expanded = (glob) => {
92
+ const found = /\{([^{}]*)\}/.exec(glob);
93
+ if (!found) return [glob];
94
+ const [whole, list = ''] = found;
95
+ return list
96
+ .split(',')
97
+ .flatMap((choice) =>
98
+ expanded(glob.slice(0, found.index) + choice + glob.slice(found.index + whole.length))
99
+ );
100
+ };
101
+
102
+ /**
103
+ * The pattern a workspace glob names, from the folder of the package.json that lists it: `**` for
104
+ * any depth and `*` for one folder's name.
105
+ *
106
+ * @param {string} folder
107
+ * @param {string} glob
108
+ */
109
+ const workspacePattern = (folder, glob) => {
110
+ const path = `${folder === '' ? '' : `${folder}/`}${glob.replace(/^\.\//, '').replace(/\/+$/, '')}`;
111
+ const source = path
112
+ .split('/')
113
+ .map((part) =>
114
+ part === '**'
115
+ ? '.*'
116
+ : part.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')
117
+ )
118
+ .join('/');
119
+ return new RegExp(`^${source}$`);
120
+ };
121
+
122
+ /**
123
+ * The workspace globs a package.json lists, as an array or under `packages`, or none.
124
+ *
125
+ * @param {string} text
126
+ * @returns {string[]}
127
+ */
128
+ const workspacesOf = (text) => {
129
+ /** @type {unknown} */
130
+ let manifest;
131
+ try {
132
+ manifest = JSON.parse(text);
133
+ } catch {
134
+ return [];
135
+ }
136
+ if (typeof manifest !== 'object' || manifest === null || !('workspaces' in manifest)) return [];
137
+ /** @type {unknown} */
138
+ const listed = manifest.workspaces;
139
+ /** @type {unknown} */
140
+ const globs =
141
+ typeof listed === 'object' && listed !== null && 'packages' in listed
142
+ ? listed.packages
143
+ : listed;
144
+ return Array.isArray(globs) ? globs.filter((glob) => typeof glob === 'string') : [];
145
+ };
146
+
147
+ /**
148
+ * The folders that are package roots, from the package.json files a repository holds, each by its
149
+ * folder: the repository's root, and each folder with a package.json of its own that no package
150
+ * above it lists as a workspace, since a workspace shares its root's `.npmrc`. As npm reads the
151
+ * globs, a brace list is expanded and a `!` entry leaves out what the others matched, so a folder it
152
+ * leaves out is a package root of its own.
153
+ *
154
+ * @param {ReadonlyMap<string, string>} manifests
155
+ * @returns {string[]}
156
+ */
157
+ export function packageRootsOf(manifests) {
158
+ const folders = [...manifests.keys()]
159
+ .map((path) => (path === 'package.json' ? '' : path.slice(0, -'/package.json'.length)))
160
+ .sort((a, b) => b.length - a.length);
161
+ const lists = new Map(
162
+ folders.map((folder) => {
163
+ const globs = workspacesOf(
164
+ manifests.get(folder === '' ? 'package.json' : `${folder}/package.json`) ?? ''
165
+ ).flatMap(expanded);
166
+ const pattern = (/** @type {string} */ glob) => workspacePattern(folder, glob);
167
+ return [
168
+ folder,
169
+ {
170
+ declares: globs.length > 0,
171
+ included: globs.filter((glob) => !glob.startsWith('!')).map(pattern),
172
+ excluded: globs
173
+ .filter((glob) => glob.startsWith('!'))
174
+ .map((glob) => pattern(glob.slice(1))),
175
+ },
176
+ ];
177
+ })
178
+ );
179
+ const above = (/** @type {string} */ folder) =>
180
+ folders.filter(
181
+ (other) => other !== folder && (other === '' || folder.startsWith(`${other}/`))
182
+ );
183
+ // A folder is a workspace of the nearest package above it whose globs list it, unless that
184
+ // package's `!` entries leave it out. One that declares workspaces of its own is a package root,
185
+ // since npm reads only one level of workspaces, from the root it runs in.
186
+ const isWorkspace = (/** @type {string} */ folder) => {
187
+ for (const other of above(folder)) {
188
+ const list = lists.get(other);
189
+ if (list?.included.some((pattern) => pattern.test(folder)))
190
+ return !list.excluded.some((pattern) => pattern.test(folder));
191
+ }
192
+ return false;
193
+ };
194
+ return folders
195
+ .filter(
196
+ (folder) =>
197
+ folder === '' || lists.get(folder)?.declares === true || !isWorkspace(folder)
198
+ )
199
+ .sort((a, b) => a.length - b.length);
200
+ }
201
+
202
+ /**
203
+ * The settings an ENV instruction's words give, each by its npm name, such as `allow-git`, with the
204
+ * value it is given, in both forms ENV takes.
205
+ *
206
+ * @param {string} rest
207
+ * @returns {Map<string, string>}
208
+ */
209
+ const envSettings = (rest) => {
210
+ const pairs = [...rest.matchAll(/(\S+?)=("[^"]*"|'[^']*'|\S*)/g)].map(
211
+ ([, key = '', value = '']) => [key, value.replace(/^(["'])(.*)\1$/, '$2')]
212
+ );
213
+ const legacy = /^(\S+)\s+(\S.*)$/.exec(rest.trim());
214
+ const all = pairs.length > 0 ? pairs : legacy ? [[legacy[1] ?? '', legacy[2] ?? '']] : [];
215
+ /** @type {Map<string, string>} */
216
+ const settings = new Map();
217
+ for (const [key = '', value = ''] of all) {
218
+ const named = ENV_NAME.exec(key);
219
+ if (named) settings.set((named[1] ?? '').toLowerCase().replace(/_/g, '-'), value.trim());
220
+ }
221
+ return settings;
222
+ };
223
+
224
+ /**
225
+ * A folder in the image, from where a stage stands and a path that may be relative to it, with no
226
+ * slash at its end but the root's own.
227
+ *
228
+ * @param {string} from
229
+ * @param {string} path
230
+ */
231
+ const folderAt = (from, path) => {
232
+ const whole = path.startsWith('/') ? path : `${from.replace(/\/$/, '')}/${path}`;
233
+ /** @type {string[]} */
234
+ const parts = [];
235
+ for (const part of whole.split('/')) {
236
+ if (part === '..') parts.pop();
237
+ else if (part !== '' && part !== '.') parts.push(part);
238
+ }
239
+ return `/${parts.join('/')}`;
240
+ };
241
+
242
+ /**
243
+ * Whether a COPY or ADD instruction's words copy a `.npmrc` into the folder the stage runs in,
244
+ * named as one of its sources, so npm reads it there. A copy of a whole folder does not count,
245
+ * since a `.dockerignore` may leave the file out, and nor does a copy to another folder.
246
+ *
247
+ * @param {string} rest
248
+ * @param {string} workdir
249
+ */
250
+ const copiesNpmrc = (rest, workdir) => {
251
+ const words = rest
252
+ .split(/\s+/)
253
+ .filter((word) => word !== '' && !word.startsWith('--'))
254
+ .map((word) => word.replace(/["',[\]]/g, ''))
255
+ .filter(Boolean);
256
+ const target = words.at(-1) ?? '';
257
+ const into = folderAt(workdir, target.replace(/(?:^|\/)\.npmrc$/, '') || '.');
258
+ return (
259
+ words.slice(0, -1).some((word) => /(?:^|\/)\.npmrc$/.test(word)) &&
260
+ into === folderAt(workdir, '.')
261
+ );
262
+ };
263
+
264
+ /**
265
+ * Each instruction of a Dockerfile with the line it starts on: continued lines joined past any
266
+ * comment or blank line among them, as Docker joins them, comment lines dropped, and a heredoc's body kept
267
+ * with the RUN that opens it.
268
+ *
269
+ * @param {string} text
270
+ * @returns {{ text: string, line: number }[]}
271
+ */
272
+ const instructionsOf = (text) => {
273
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
274
+ /** @type {{ text: string, line: number }[]} */
275
+ const instructions = [];
276
+ let at = 0;
277
+ while (at < lines.length) {
278
+ const start = at;
279
+ let joined = lines[at] ?? '';
280
+ at += 1;
281
+ if (/^\s*#/.test(joined) || joined.trim() === '') continue;
282
+ while (/\\[ \t]*$/.test(joined) && at < lines.length) {
283
+ const next = lines[at] ?? '';
284
+ at += 1;
285
+ joined = joined.replace(/\\[ \t]*$/, '\\');
286
+ if (!/^\s*#/.test(next) && next.trim() !== '')
287
+ joined = `${joined.slice(0, -1)} ${next}`;
288
+ }
289
+ const heredoc = /(?:^|\s)<<-?(["']?)([A-Za-z_]\w*)\1/.exec(joined);
290
+ const end = heredoc
291
+ ? lines.findIndex((line, index) => index >= at && line.trim() === heredoc[2])
292
+ : -1;
293
+ if (end >= 0) {
294
+ joined = `${joined}\n${lines.slice(at, end).join('\n')}`;
295
+ at = end + 1;
296
+ }
297
+ instructions.push({ text: joined, line: start + 1 });
298
+ }
299
+ return instructions;
300
+ };
301
+
302
+ /**
303
+ * The stage a FROM starts: the image or earlier stage it builds on, and the name it gives itself.
304
+ *
305
+ * @param {string} rest
306
+ */
307
+ const stageOf = (rest) => {
308
+ const words = rest.split(/\s+/).filter((word) => word !== '' && !word.startsWith('--'));
309
+ const as = words.findIndex((word) => word.toLowerCase() === 'as');
310
+ return { base: words[0] ?? '', name: as >= 0 ? words[as + 1] : undefined };
311
+ };
312
+
313
+ /**
314
+ * What a stage has set before a RUN: install scripts off, git and URL dependencies each stopped,
315
+ * the folder it runs in, and the folder a `.npmrc` that holds all three was copied into, if any.
316
+ *
317
+ * @typedef {{ scripts: boolean, git: boolean, remote: boolean, workdir: string, npmrc: string | undefined }} Held
318
+ */
319
+
320
+ /** A stage that has set nothing, as one built on an image starts, in the image's root. */
321
+ const UNSET = Object.freeze({
322
+ scripts: false,
323
+ git: false,
324
+ remote: false,
325
+ workdir: '/',
326
+ npmrc: undefined,
327
+ });
328
+
329
+ /**
330
+ * What a FROM's stage starts with, and the name it is known by: what an earlier stage held when it
331
+ * builds on one, and nothing when it builds on an image.
332
+ *
333
+ * @param {string} rest
334
+ * @param {ReadonlyMap<string, Held>} stages
335
+ */
336
+ const entering = (rest, stages) => {
337
+ const { base, name } = stageOf(rest);
338
+ return { held: { ...(stages.get(base.toLowerCase()) ?? UNSET) }, stage: name?.toLowerCase() };
339
+ };
340
+
341
+ /**
342
+ * Whether an instruction runs a command in the image, as RUN does now and ONBUILD RUN does in a
343
+ * later build.
344
+ *
345
+ * @param {string} keyword
346
+ * @param {string} rest
347
+ */
348
+ const runs = (keyword, rest) =>
349
+ keyword === 'RUN' || (keyword === 'ONBUILD' && /^RUN\b/i.test(rest));
350
+
351
+ /**
352
+ * What a stage holds after an ENV instruction: each of the three settings it gives counts where it
353
+ * gives the value that stops what the setting governs, and is unset where it gives any other.
354
+ *
355
+ * @param {Held} held
356
+ * @param {string} rest
357
+ * @returns {Held}
358
+ */
359
+ const afterEnv = (held, rest) => {
360
+ const settings = envSettings(rest);
361
+ const set = (
362
+ /** @type {string} */ key,
363
+ /** @type {string} */ needed,
364
+ /** @type {boolean} */ was
365
+ ) => (settings.has(key) ? settings.get(key) === needed : was);
366
+ return {
367
+ ...held,
368
+ scripts: set('ignore-scripts', 'true', held.scripts),
369
+ git: set('allow-git', 'none', held.git),
370
+ remote: set('allow-remote', 'none', held.remote),
371
+ };
372
+ };
373
+
374
+ /**
375
+ * What is wrong with a RUN, given what its stage holds as it runs: install scripts not yet off, and
376
+ * git and URL dependencies not yet stopped, unless the `.npmrc` was copied into the folder it runs
377
+ * in.
378
+ *
379
+ * @param {string} where
380
+ * @param {Held} held
381
+ * @param {string} rest
382
+ * @returns {string[]}
383
+ */
384
+ const runProblems = (where, held, rest) => {
385
+ if (held.npmrc === held.workdir) return [];
386
+ const command = rest.split('\n')[0]?.trim() ?? '';
387
+ return [
388
+ ...(held.scripts
389
+ ? []
390
+ : [
391
+ `${where} runs before its stage sets ${SETTING}=true with ENV or copies in the .npmrc\n ${command}`,
392
+ ]),
393
+ ...(held.git && held.remote
394
+ ? []
395
+ : [
396
+ `${where} runs before its stage stops git and URL dependencies, with ${FETCH_SETTINGS} set to none by ENV or the .npmrc copied in\n ${command}`,
397
+ ]),
398
+ ];
399
+ };
400
+
401
+ /**
402
+ * Each RUN of a Dockerfile, ONBUILD RUN among them, that comes before its stage holds npm's three
403
+ * settings, whatever it runs, since a script it calls may run npm: install scripts turned off, and
404
+ * git and URL dependencies stopped, each set with ENV, or the `.npmrc` that holds all three copied
405
+ * into the folder the RUN runs in. An image build often copies only a `package.json` and its
406
+ * lockfile before installing, so the repository's `.npmrc` counts only where the stage copies it.
407
+ * ARG does not count, since a build
408
+ * argument can be set otherwise when the image is built. A FROM starts a stage with nothing set,
409
+ * unless it builds on an earlier stage, whose settings and files it inherits.
410
+ *
411
+ * @param {string} path
412
+ * @param {string} text
413
+ * @returns {string[]}
414
+ */
415
+ export function dockerfileProblems(path, text) {
416
+ /** @type {string[]} */
417
+ const problems = [];
418
+ /** @type {Map<string, Held>} */
419
+ const stages = new Map();
420
+ /** @type {string | undefined} */
421
+ let stage;
422
+ /** @type {Held} */
423
+ let held = { ...UNSET };
424
+ for (const { text: instruction, line } of instructionsOf(text)) {
425
+ const [, word = '', rest = ''] = /^\s*(\S+)\s*([\s\S]*)$/.exec(instruction) ?? [];
426
+ const keyword = word.toUpperCase();
427
+ if (keyword === 'FROM') {
428
+ if (stage !== undefined) stages.set(stage, held);
429
+ ({ held, stage } = entering(rest, stages));
430
+ } else if (keyword === 'ENV') held = afterEnv(held, rest);
431
+ else if (keyword === 'WORKDIR')
432
+ held = { ...held, workdir: folderAt(held.workdir, rest.trim()) };
433
+ else if ((keyword === 'COPY' || keyword === 'ADD') && copiesNpmrc(rest, held.workdir))
434
+ held = { ...held, npmrc: held.workdir };
435
+ else if (runs(keyword, rest)) problems.push(...runProblems(`${path}:${line}`, held, rest));
436
+ }
437
+ return problems;
438
+ }
439
+
440
+ /**
441
+ * The npm flag and environment setting that name install scripts, each built from its parts, so
442
+ * this file holds neither whole and the check can read it like any other. npm reads the setting's
443
+ * name in any case, with an underscore or a hyphen after the prefix.
444
+ */
445
+ const FLAG = ['--ignore', '-scripts'].join('');
446
+ const SETTING = ['npm_config', '_ignore', '_scripts'].join('');
447
+ const SETTING_SOURCE = `${SETTING.slice(0, -'_scripts'.length)}[-_]scripts`;
448
+
449
+ /**
450
+ * The environment names of the three settings, each with what follows the prefix, so `allow_git`
451
+ * reads as `allow-git`. npm reads them in any case, with an underscore or a hyphen between words.
452
+ */
453
+ const ENV_NAME = /^npm_config[-_]((?:ignore|allow)[-_](?:scripts|git|remote))$/i;
454
+
455
+ /** The two fetch settings as a Dockerfile sets them, named in a message. */
456
+ const FETCH_SETTINGS = ['allow_git', 'allow_remote']
457
+ .map((name) => `npm_config_${name}`)
458
+ .join(' and ');
459
+
460
+ /** A value with its quotes taken off, in lower case. */
461
+ const plain = (/** @type {string} */ value) => value.replace(/^(["'])(.*)\1$/, '$2').toLowerCase();
462
+
463
+ /**
464
+ * The flag given a value with `=`, which npm reads as false for anything but true, and the flag
465
+ * followed by a word npm reads as false, quoted or not.
466
+ */
467
+ const FLAG_VALUE = new RegExp(`${FLAG}=("[^"]*"|'[^']*'|[^\\s;&|)]*)`, 'gi');
468
+ const FLAG_FALSE = new RegExp(
469
+ `${FLAG}\\s+(["']?)(?:false|0|null)\\1(?![\\w-])|--no${FLAG.slice(1)}\\b`,
470
+ 'i'
471
+ );
472
+
473
+ /**
474
+ * The environment setting given a value with `=` or `:`, quoted or not, in any case. An unquoted
475
+ * value ends at a space, a shell operator, a bracket, a backslash, a backtick or a quote.
476
+ */
477
+ const VALUE = `("[^"\\n]*"|'[^'\\n]*'|[^\\s;&|,})\\]\\\\\\x60"']*)`;
478
+
479
+ /**
480
+ * The separator between a setting's name and its value: a colon or an equals sign, after a quote
481
+ * and a closing bracket where code reads it as a key, such as `env["name"] = value`, and with the
482
+ * rest of a comparison such as `===` passed over, so a test of the value reads the value it tests.
483
+ */
484
+ const SEPARATOR = `["']?\\]?\\s*[:=]=*\\s*`;
485
+ const SETTING_VALUE = new RegExp(`${SETTING_SOURCE}${SEPARATOR}${VALUE}`, 'gi');
486
+
487
+ /**
488
+ * The flags and environment settings that let npm fetch dependencies from git or a URL, each given
489
+ * a value, which npm reads in place of the `.npmrc`'s whenever it is anything but none. Each is
490
+ * built from its parts, as the install scripts flag is.
491
+ */
492
+ const FETCH_FLAG_VALUE = new RegExp(
493
+ `${['--allow', '-'].join('')}(?:git|remote)(?:=|\\s+)("[^"]*"|'[^']*'|[^\\s;&|)]*)`,
494
+ 'gi'
495
+ );
496
+ const FETCH_SETTING_VALUE = new RegExp(
497
+ `${['npm_config', '[-_]allow'].join('')}[-_](?:git|remote)${SEPARATOR}${VALUE}`,
498
+ 'gi'
499
+ );
500
+
501
+ /** npm's subcommands that install, in every spelling it accepts. */
502
+ const INSTALLS =
503
+ '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';
504
+
505
+ /** An npm install on a line that names another project with `--prefix` or `-C`. */
506
+ const INSTALL = new RegExp(`(?:^|[\\s;&|(])npm\\s(?:.*\\s)?(?:${INSTALLS})(?=\\s|$)`);
507
+ const ELSEWHERE =
508
+ /\s(?:--prefix(?:=|\s)|-C\s|-g(?=\s|$)|--global(?=[\s=]|$)|--location(?:=|\s+)global\b)/;
509
+
510
+ /**
511
+ * A write to the project's own `.npmrc` by npm's config command: `edit` of the whole file, or `set`
512
+ * or `delete` of one of the three settings, which would change what the check read from the file
513
+ * after it read it.
514
+ */
515
+ const CONFIG_WRITE = /(?:^|[\s;&|(])npm\s+(?:.*\s)?(?:config|c)\s+(set|delete|rm|edit)\b(.*)$/;
516
+ const PROJECT = /\s(?:--location|-L)(?:=|\s+)project\b/;
517
+ const HELD_KEY = /\b(?:ignore-scripts|allow-git|allow-remote)\b/;
518
+
519
+ /**
520
+ * Whether a line writes one of the three settings into the project's `.npmrc`.
521
+ *
522
+ * @param {string} line
523
+ */
524
+ const writesProject = (line) => {
525
+ const found = CONFIG_WRITE.exec(line);
526
+ if (!found || !PROJECT.test(line)) return false;
527
+ return found[1] === 'edit' || HELD_KEY.test(found[2] ?? '');
528
+ };
529
+
530
+ /** npm's and npx's options that take a value, so the value is not read as the tool. */
531
+ const VALUED = new Set([
532
+ '--prefix',
533
+ '--workspace',
534
+ '-w',
535
+ '-C',
536
+ '--cache',
537
+ '--loglevel',
538
+ '--userconfig',
539
+ '--registry',
540
+ '--scope',
541
+ '--package',
542
+ '-p',
543
+ '--call',
544
+ '-c',
545
+ ]);
546
+
547
+ /**
548
+ * The words that may come before a command where it starts a line or a script: a list item's dash,
549
+ * a key such as `run:` or a script's name, a Dockerfile's RUN, a variable set for the command, and
550
+ * the commands that run another, such as `sudo` and `env`.
551
+ */
552
+ const LEAD = /^(?:-|[\w.-]+:|RUN|ONBUILD|sudo|exec|env|time|command|[A-Za-z_]\w*=\S*)$/;
553
+
554
+ /** Whether a word runs a tool, by name or by a path that ends in it. */
555
+ const isTool = (/** @type {string} */ word, /** @type {string} */ tool) =>
556
+ word === tool || word.endsWith(`/${tool}`);
557
+
558
+ /** Where the first word from `from` that is not an option sits, passing over an option's value. */
559
+ const operandAt = (/** @type {readonly string[]} */ words, /** @type {number} */ from) => {
560
+ for (let at = from; at < words.length; at += 1) {
561
+ const word = words[at] ?? '';
562
+ if (word === '--') return at + 1 < words.length ? at + 1 : -1;
563
+ if (!word.startsWith('-')) return at;
564
+ if (VALUED.has(word)) at += 1;
565
+ }
566
+ return -1;
567
+ };
568
+
569
+ /**
570
+ * Whether npx, or npm's exec command, by its own options before the tool, may fetch what it runs:
571
+ * the last of the options that say whether it may deciding, and fetching when none is given. npx
572
+ * reads `--no-install` as `--no`, and npm's exec command does not, so there it stops nothing.
573
+ *
574
+ * @param {readonly string[]} words
575
+ * @param {number} from
576
+ * @param {boolean} throughNpx
577
+ */
578
+ const mayFetch = (words, from, throughNpx) => {
579
+ let fetches = true;
580
+ for (let at = from; at < words.length; at += 1) {
581
+ const word = words[at] ?? '';
582
+ if (word === '--' || !word.startsWith('-')) break;
583
+ if (word === '--no' || word === '--yes=false' || (throughNpx && word === '--no-install'))
584
+ fetches = false;
585
+ else if (word === '--yes' || word === '-y') fetches = true;
586
+ else if (VALUED.has(word)) at += 1;
587
+ }
588
+ return fetches;
589
+ };
590
+
591
+ /**
592
+ * Whether a line runs a command that may fetch a package to run it: npx, or npm's exec command or
593
+ * its alias, whose own options leave it free to fetch, npm's create command, or its init command
594
+ * given an initializer, each read only where it starts a command, so a sentence that names one is
595
+ * passed over.
596
+ *
597
+ * @param {string} line
598
+ */
599
+ const fetchesToRun = (line) =>
600
+ line
601
+ .split(/&&|\|\||;|\||&|\$\(|`/)
602
+ .map((command) => command.split(/[\s"'()<>]+/).filter(Boolean))
603
+ .some((words) => {
604
+ const at = words.findIndex((word) => !LEAD.test(word));
605
+ const first = words[at] ?? '';
606
+ if (isTool(first, 'npx')) return mayFetch(words, at + 1, true);
607
+ if (!isTool(first, 'npm')) return false;
608
+ const sub = operandAt(words, at + 1);
609
+ const subcommand = sub < 0 ? '' : (words[sub] ?? '');
610
+ if (subcommand === 'exec' || subcommand === 'x') return mayFetch(words, sub + 1, false);
611
+ if (subcommand === 'create') return true;
612
+ if (subcommand === 'init' || subcommand === 'innit')
613
+ return operandAt(words, sub + 1) >= 0;
614
+ return false;
615
+ });
616
+ const FLAG_OFF = new RegExp(`${FLAG}(?![=\\w-])|${FLAG}=(["']?)true\\1(?![\\w-])`, 'i');
617
+
618
+ /** The flags that stop an install fetching from git and from a URL, built from their parts. */
619
+ const FETCH_OFF = ['git', 'remote'].map(
620
+ (kind) =>
621
+ new RegExp(`${['--allow', '-'].join('')}${kind}(?:=|\\s+)(["']?)none\\1(?![\\w-])`, 'i')
622
+ );
623
+
624
+ /**
625
+ * Whether a line runs an install outside the project, by `--prefix` or `-C`, or into npm's global
626
+ * folder, without the flags that hold what the project's `.npmrc` would: install scripts off, and
627
+ * git and URL dependencies stopped, by their two flags or by `--offline`, which fetches nothing.
628
+ * Each command on the line is judged by its own words.
629
+ *
630
+ * @param {string} line
631
+ */
632
+ const installsOutside = (line) =>
633
+ line
634
+ .split(/&&|\|\||;|\||&/)
635
+ .some(
636
+ (command) =>
637
+ INSTALL.test(command) &&
638
+ ELSEWHERE.test(command) &&
639
+ (!FLAG_OFF.test(command) ||
640
+ !(
641
+ /\s--offline\b/.test(command) ||
642
+ FETCH_OFF.every((flag) => flag.test(command))
643
+ ))
644
+ );
645
+
646
+ /**
647
+ * What a line does that the settings do not hold, or undefined: turns install scripts back on, with
648
+ * the flag given any value npm reads as false or negated, the environment setting given any value
649
+ * but true, or a write of one of the settings to the project's `.npmrc`. Installs outside the
650
+ * project without the flags that hold its settings. Lets npm fetch from git or a URL, with a flag
651
+ * or a setting given any value but none. Or fetches a package to run it.
652
+ *
653
+ * @param {string} line
654
+ * @returns {string | undefined}
655
+ */
656
+ const lineProblem = (line) => {
657
+ const flagOn =
658
+ FLAG_FALSE.test(line) ||
659
+ [...line.matchAll(FLAG_VALUE)].some(([, value = '']) => plain(value) !== 'true');
660
+ const setOn = [...line.matchAll(SETTING_VALUE)].some(
661
+ ([, value = '']) => plain(value) !== 'true'
662
+ );
663
+ if (flagOn || setOn || writesProject(line)) return 'turns install scripts back on';
664
+ if (installsOutside(line))
665
+ return 'installs outside the project, where its .npmrc is not read, without the flags that hold its settings';
666
+ const fetchOn = [
667
+ ...line.matchAll(FETCH_FLAG_VALUE),
668
+ ...line.matchAll(FETCH_SETTING_VALUE),
669
+ ].some(([, value = '']) => plain(value) !== 'none');
670
+ if (fetchOn) return 'lets npm fetch dependencies from git or URLs';
671
+ if (fetchesToRun(line))
672
+ return 'may fetch a package to run it, without --no, or --no-install for npx, to stop it';
673
+ return undefined;
674
+ };
675
+
676
+ /**
677
+ * Each line of a file that lets npm do what the settings stop: one that sets install scripts on, or
678
+ * git or URL dependencies allowed, by a flag or an `npm_config_` setting, one that writes a setting
679
+ * to the project's `.npmrc` with npm's config command, an install outside the project without the
680
+ * flags that hold its settings, and a run of npx, or npm's exec, create or init command, that may
681
+ * fetch a package to run it.
682
+ *
683
+ * @param {string} path
684
+ * @param {string} text
685
+ * @returns {string[]}
686
+ */
687
+ export function scriptsOnProblems(path, text) {
688
+ return text
689
+ .replace(/\r\n/g, '\n')
690
+ .split('\n')
691
+ .flatMap((line, index) => {
692
+ const problem = lineProblem(line);
693
+ return problem === undefined
694
+ ? []
695
+ : [`${path}:${index + 1} ${problem}\n ${line.trim()}`];
696
+ });
697
+ }
698
+
699
+ /** The first npm that reads `allow-git` and `allow-remote`, which the settings rely on. */
700
+ const NPM_FLOOR = [11, 14, 0];
701
+
702
+ /**
703
+ * What is wrong with the npm that runs the check, given its version: older than the first that
704
+ * reads `allow-git` and `allow-remote`, a prerelease of it included, so it would pass over both
705
+ * settings without a word. The floor is held here rather than by `engines.npm`, since Dependabot's
706
+ * npm updater reads that field and may refuse to run on an older npm.
707
+ *
708
+ * @param {string} version
709
+ * @returns {string[]}
710
+ */
711
+ export function npmFloorProblems(version) {
712
+ const written = version.trim();
713
+ // The release's own numbers end at the first hyphen, which starts a prerelease, or plus sign,
714
+ // which starts build details. Found by a plain search, so a long version costs one pass.
715
+ const cut = [...written].findIndex((char) => char === '-' || char === '+');
716
+ const release = cut < 0 ? written : written.slice(0, cut);
717
+ const prerelease = cut >= 0 && written[cut] === '-';
718
+ const parts = release.split('.').map(Number);
719
+ const differs = NPM_FLOOR.findIndex((part, index) => (parts[index] ?? 0) !== part);
720
+ // A prerelease of the floor itself comes before the release, so it may not read the settings.
721
+ const enough = differs < 0 ? !prerelease : (parts[differs] ?? 0) > (NPM_FLOOR[differs] ?? 0);
722
+ return enough
723
+ ? []
724
+ : [
725
+ `npm ${written} is older than ${NPM_FLOOR.join('.')}, the first that reads allow-git and allow-remote, so it would pass over both`,
726
+ ];
727
+ }
@@ -0,0 +1,2 @@
1
+ export { installProblems, isDockerfile, repositoryRoot } from "./repository.mjs";
2
+ export { dockerfileProblems, npmFloorProblems, 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,69 @@
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 holds npm's three
24
+ * settings, whatever it runs, since a script it calls may run npm: install scripts turned off, and
25
+ * git and URL dependencies stopped, each set with ENV, or the `.npmrc` that holds all three copied
26
+ * into the folder the RUN runs in. An image build often copies only a `package.json` and its
27
+ * lockfile before installing, so the repository's `.npmrc` counts only where the stage copies it.
28
+ * ARG does not count, since a build
29
+ * argument can be set otherwise when the image is built. A FROM starts a stage with nothing set,
30
+ * unless it builds on an earlier stage, whose settings and files it inherits.
31
+ *
32
+ * @param {string} path
33
+ * @param {string} text
34
+ * @returns {string[]}
35
+ */
36
+ export function dockerfileProblems(path: string, text: string): string[];
37
+ /**
38
+ * Each line of a file that lets npm do what the settings stop: one that sets install scripts on, or
39
+ * git or URL dependencies allowed, by a flag or an `npm_config_` setting, one that writes a setting
40
+ * to the project's `.npmrc` with npm's config command, an install outside the project without the
41
+ * flags that hold its settings, and a run of npx, or npm's exec, create or init command, that may
42
+ * fetch a package to run it.
43
+ *
44
+ * @param {string} path
45
+ * @param {string} text
46
+ * @returns {string[]}
47
+ */
48
+ export function scriptsOnProblems(path: string, text: string): string[];
49
+ /**
50
+ * What is wrong with the npm that runs the check, given its version: older than the first that
51
+ * reads `allow-git` and `allow-remote`, a prerelease of it included, so it would pass over both
52
+ * settings without a word. The floor is held here rather than by `engines.npm`, since Dependabot's
53
+ * npm updater reads that field and may refuse to run on an older npm.
54
+ *
55
+ * @param {string} version
56
+ * @returns {string[]}
57
+ */
58
+ export function npmFloorProblems(version: string): string[];
59
+ /**
60
+ * What a stage has set before a RUN: install scripts off, git and URL dependencies each stopped,
61
+ * the folder it runs in, and the folder a `.npmrc` that holds all three was copied into, if any.
62
+ */
63
+ export type Held = {
64
+ scripts: boolean;
65
+ git: boolean;
66
+ remote: boolean;
67
+ workdir: string;
68
+ npmrc: string | undefined;
69
+ };