@jasonsdevspace/repo-check 0.1.0 → 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/README.md CHANGED
@@ -26,23 +26,57 @@ rather than reading the commands it runs.
26
26
  a folder out, so a folder left out is a package root of its own, and so is a workspace that
27
27
  declares workspaces of its own, since npm reads only one level of them.
28
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.
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.
46
80
 
47
81
  ## Lifecycle scripts under the rule
48
82
 
@@ -78,11 +112,14 @@ install given `--prefix` or `-C` without it is refused.
78
112
  quoted value unquoted, an inline `;` or `#` comment left out, and a key written alone read as
79
113
  true.
80
114
  - **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.
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.
86
123
 
87
124
  It reads every file git tracks and every new one git would add, leaving out what the repository
88
125
  ignores.
@@ -95,9 +132,9 @@ printf '\nignore-scripts=true\nallow-git=none\nallow-remote=none\n' >> .npmrc
95
132
  ```
96
133
 
97
134
  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.
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.
101
138
 
102
139
  Run it in `verify`, beside the other checks, and in CI:
103
140
 
@@ -113,11 +150,13 @@ Run it in `verify`, beside the other checks, and in CI:
113
150
  ## What a failure looks like
114
151
 
115
152
  ```text
116
- Install check failed. Each place below lets npm run install scripts:
153
+ Install check failed. Each place below lets npm run install scripts or fetch what it should not:
117
154
 
118
155
  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
156
+ Dockerfile:9 runs before its stage sets npm_config_ignore_scripts=true with ENV or copies in the .npmrc
120
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
121
160
  ```
122
161
 
123
162
  Each problem names the file, and the line where there is one. The command exits 0 when the
@@ -132,8 +171,12 @@ prints, and an empty list when there are none. The rules it is built from are ex
132
171
  - `packageRootsOf(manifests)` gives the package roots, by folder, from a map of each `package.json`
133
172
  path to its text.
134
173
  - `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.
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.
137
180
  - `isDockerfile(path)` says whether a path names a Dockerfile, and `repositoryRoot(folder)` gives
138
181
  the top of the git repository a folder sits in.
139
182
 
@@ -2,12 +2,16 @@
2
2
  /**
3
3
  * Fails when the repository it is run in lets npm run install scripts or fetch git and URL
4
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.
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.
7
9
  * It exits 0 on a pass, 1 on a refusal, and 2 with how to run it when given an argument or run
8
10
  * outside a git repository.
9
11
  */
10
- import { installProblems, repositoryRoot } from '../src/index.mjs';
12
+ import { execFileSync } from 'node:child_process';
13
+
14
+ import { installProblems, npmFloorProblems, repositoryRoot } from '../src/index.mjs';
11
15
 
12
16
  if (process.argv.length > 2) {
13
17
  console.error(
@@ -19,13 +23,25 @@ if (process.argv.length > 2) {
19
23
  /** @type {string[]} */
20
24
  let failures;
21
25
  try {
22
- failures = installProblems(repositoryRoot(process.cwd()));
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()))];
23
37
  } catch (error) {
24
38
  console.error(`check-installs: ${error instanceof Error ? error.message : String(error)}`);
25
39
  process.exit(2);
26
40
  }
27
41
  if (failures.length > 0) {
28
- console.error(`Install check failed. Each place below lets npm run install scripts:\n`);
42
+ console.error(
43
+ `Install check failed. Each place below lets npm run install scripts or fetch what it should not:\n`
44
+ );
29
45
  console.error(failures.join('\n'));
30
46
  process.exit(1);
31
47
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
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.",
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
5
  "keywords": [
6
6
  "npm",
7
7
  "install-scripts",
@@ -24,7 +24,7 @@
24
24
  "type": "module",
25
25
  "sideEffects": false,
26
26
  "engines": {
27
- "node": ">=24"
27
+ "node": ">=24.18"
28
28
  },
29
29
  "bin": {
30
30
  "check-installs": "./bin/check-installs.mjs"
package/src/index.mjs CHANGED
@@ -3,4 +3,10 @@
3
3
  * scripts, which the `check-installs` command runs, and the rules it is built from.
4
4
  */
5
5
  export { installProblems, isDockerfile, repositoryRoot } from './repository.mjs';
6
- export { dockerfileProblems, npmrcProblems, packageRootsOf, scriptsOnProblems } from './rules.mjs';
6
+ export {
7
+ dockerfileProblems,
8
+ npmFloorProblems,
9
+ npmrcProblems,
10
+ packageRootsOf,
11
+ scriptsOnProblems,
12
+ } from './rules.mjs';
package/src/rules.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  /**
2
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.
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.
6
8
  */
7
9
 
8
10
  /**
@@ -198,24 +200,65 @@ export function packageRootsOf(manifests) {
198
200
  }
199
201
 
200
202
  /**
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
+ * 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.
203
205
  *
204
206
  * @param {string} rest
205
- * @returns {boolean | undefined}
207
+ * @returns {Map<string, string>}
206
208
  */
207
- const scriptsSetting = (rest) => {
209
+ const envSettings = (rest) => {
208
210
  const pairs = [...rest.matchAll(/(\S+?)=("[^"]*"|'[^']*'|\S*)/g)].map(
209
211
  ([, key = '', value = '']) => [key, value.replace(/^(["'])(.*)\1$/, '$2')]
210
212
  );
211
213
  const legacy = /^(\S+)\s+(\S.*)$/.exec(rest.trim());
212
214
  const all = pairs.length > 0 ? pairs : legacy ? [[legacy[1] ?? '', legacy[2] ?? '']] : [];
213
- /** @type {boolean | undefined} */
214
- let setting;
215
+ /** @type {Map<string, string>} */
216
+ const settings = new Map();
215
217
  for (const [key = '', value = ''] of all) {
216
- if (SETTING_NAME.test(key)) setting = value.trim() === 'true';
218
+ const named = ENV_NAME.exec(key);
219
+ if (named) settings.set((named[1] ?? '').toLowerCase().replace(/_/g, '-'), value.trim());
217
220
  }
218
- return setting;
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
+ );
219
262
  };
220
263
 
221
264
  /**
@@ -268,15 +311,31 @@ const stageOf = (rest) => {
268
311
  };
269
312
 
270
313
  /**
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.
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.
273
332
  *
274
333
  * @param {string} rest
275
- * @param {ReadonlyMap<string, boolean>} stages
334
+ * @param {ReadonlyMap<string, Held>} stages
276
335
  */
277
336
  const entering = (rest, stages) => {
278
337
  const { base, name } = stageOf(rest);
279
- return { off: stages.get(base.toLowerCase()) ?? false, stage: name?.toLowerCase() };
338
+ return { held: { ...(stages.get(base.toLowerCase()) ?? UNSET) }, stage: name?.toLowerCase() };
280
339
  };
281
340
 
282
341
  /**
@@ -290,11 +349,64 @@ const runs = (keyword, rest) =>
290
349
  keyword === 'RUN' || (keyword === 'ONBUILD' && /^RUN\b/i.test(rest));
291
350
 
292
351
  /**
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.
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.
298
410
  *
299
411
  * @param {string} path
300
412
  * @param {string} text
@@ -303,22 +415,24 @@ const runs = (keyword, rest) =>
303
415
  export function dockerfileProblems(path, text) {
304
416
  /** @type {string[]} */
305
417
  const problems = [];
306
- /** @type {Map<string, boolean>} */
418
+ /** @type {Map<string, Held>} */
307
419
  const stages = new Map();
308
420
  /** @type {string | undefined} */
309
421
  let stage;
310
- let off = false;
422
+ /** @type {Held} */
423
+ let held = { ...UNSET };
311
424
  for (const { text: instruction, line } of instructionsOf(text)) {
312
425
  const [, word = '', rest = ''] = /^\s*(\S+)\s*([\s\S]*)$/.exec(instruction) ?? [];
313
426
  const keyword = word.toUpperCase();
314
427
  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
- );
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));
322
436
  }
323
437
  return problems;
324
438
  }
@@ -331,7 +445,17 @@ export function dockerfileProblems(path, text) {
331
445
  const FLAG = ['--ignore', '-scripts'].join('');
332
446
  const SETTING = ['npm_config', '_ignore', '_scripts'].join('');
333
447
  const SETTING_SOURCE = `${SETTING.slice(0, -'_scripts'.length)}[-_]scripts`;
334
- const SETTING_NAME = new RegExp(`^${SETTING_SOURCE}$`, 'i');
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 ');
335
459
 
336
460
  /** A value with its quotes taken off, in lower case. */
337
461
  const plain = (/** @type {string} */ value) => value.replace(/^(["'])(.*)\1$/, '$2').toLowerCase();
@@ -350,8 +474,27 @@ const FLAG_FALSE = new RegExp(
350
474
  * The environment setting given a value with `=` or `:`, quoted or not, in any case. An unquoted
351
475
  * value ends at a space, a shell operator, a bracket, a backslash, a backtick or a quote.
352
476
  */
353
- const SETTING_VALUE = new RegExp(
354
- `${SETTING_SOURCE}["']?\\s*[:=]\\s*("[^"\\n]*"|'[^'\\n]*'|[^\\s;&|,})\\]\\\\\\x60"']*)`,
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}`,
355
498
  'gi'
356
499
  );
357
500
 
@@ -361,14 +504,181 @@ const INSTALLS =
361
504
 
362
505
  /** An npm install on a line that names another project with `--prefix` or `-C`. */
363
506
  const INSTALL = new RegExp(`(?:^|[\\s;&|(])npm\\s(?:.*\\s)?(?:${INSTALLS})(?=\\s|$)`);
364
- const ELSEWHERE = /\s(?:--prefix(?:=|\s)|-C\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
+ });
365
616
  const FLAG_OFF = new RegExp(`${FLAG}(?![=\\w-])|${FLAG}=(["']?)true\\1(?![\\w-])`, 'i');
366
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
+
367
676
  /**
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.
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.
372
682
  *
373
683
  * @param {string} path
374
684
  * @param {string} text
@@ -379,14 +689,39 @@ export function scriptsOnProblems(path, text) {
379
689
  .replace(/\r\n/g, '\n')
380
690
  .split('\n')
381
691
  .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()}`];
692
+ const problem = lineProblem(line);
693
+ return problem === undefined
694
+ ? []
695
+ : [`${path}:${index + 1} ${problem}\n ${line.trim()}`];
391
696
  });
392
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
+ }
package/types/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { installProblems, isDockerfile, repositoryRoot } from "./repository.mjs";
2
- export { dockerfileProblems, npmrcProblems, packageRootsOf, scriptsOnProblems } from "./rules.mjs";
2
+ export { dockerfileProblems, npmFloorProblems, npmrcProblems, packageRootsOf, scriptsOnProblems } from "./rules.mjs";
package/types/rules.d.mts CHANGED
@@ -20,11 +20,14 @@ export function npmrcProblems(path: string, text: string, packageRoot: boolean):
20
20
  */
21
21
  export function packageRootsOf(manifests: ReadonlyMap<string, string>): string[];
22
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.
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.
28
31
  *
29
32
  * @param {string} path
30
33
  * @param {string} text
@@ -32,13 +35,35 @@ export function packageRootsOf(manifests: ReadonlyMap<string, string>): string[]
32
35
  */
33
36
  export function dockerfileProblems(path: string, text: string): string[];
34
37
  /**
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.
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.
39
43
  *
40
44
  * @param {string} path
41
45
  * @param {string} text
42
46
  * @returns {string[]}
43
47
  */
44
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
+ };