@neon-pixels/scripts 0.2.0 → 0.4.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 +122 -3
- package/dist/allowlist-B_zgqKrH.js +151 -0
- package/dist/audit-gate.js +50 -175
- package/dist/check-absent-dependency.js +161 -0
- package/dist/check-migration-drift.js +128 -0
- package/dist/check-migration-snapshots.js +94 -0
- package/dist/{workflow-command-BkYMh3G8.js → client-fLNszLcv.js} +18 -8
- package/dist/options-C_apa01R.js +82 -0
- package/dist/report-lighthouse-failure.js +408 -0
- package/dist/should-deploy.js +16 -10
- package/dist/sync-templates.js +297 -0
- package/dist/verify-netlify-deploy.js +29 -6
- package/dist/workflow-command-Bb1eVLow.js +16 -0
- package/package.json +9 -3
- package/templates/base/.github/dependabot.yml +34 -0
- package/templates/base/.gitleaks.toml +37 -0
- package/templates/base/.husky/post-merge +4 -0
- package/templates/base/.husky/pre-commit +10 -0
- package/templates/base/.husky/pre-push +9 -0
- package/templates/base/.nvmrc +1 -0
- package/templates/base/package-fields.json +5 -0
- package/templates/nuxt/.husky/pre-push +17 -0
- package/templates/vitepress/.github/dependabot.yml +55 -0
package/README.md
CHANGED
|
@@ -10,15 +10,20 @@ pnpm add -D @neon-pixels/scripts
|
|
|
10
10
|
|
|
11
11
|
## `np-audit-gate`
|
|
12
12
|
|
|
13
|
-
Audits production dependencies and fails on any high or critical advisory that is not on your reviewed allowlist. Moderate and low advisories are counted in the summary but never fail the gate.
|
|
13
|
+
Audits production dependencies (all dependencies with `--include-dev`) and fails on any high or critical advisory that is not on your reviewed allowlist. Moderate and low advisories are counted in the summary but never fail the gate.
|
|
14
14
|
|
|
15
15
|
```sh
|
|
16
16
|
pnpm exec np-audit-gate
|
|
17
17
|
pnpm exec np-audit-gate --allowlist path/to/audit-allowlist.json
|
|
18
|
+
pnpm exec np-audit-gate --include-dev
|
|
18
19
|
```
|
|
19
20
|
|
|
20
21
|
Run it from the project root. It picks the package manager from the lockfile (`pnpm-lock.yaml`, `package-lock.json`, or `npm-shrinkwrap.json`) and runs `pnpm audit --prod --json` or `npm audit --omit=dev --json`. A project with no lockfile, or with both kinds, fails.
|
|
21
22
|
|
|
23
|
+
`--include-dev` audits every dependency, dev dependencies included, with `pnpm audit --json` or `npm audit --json`. Use it for a site whose framework and build tooling are all dev dependencies, so the default scope covers almost nothing. The default scope is unchanged. The allowlist format, expiry, stale-entry reporting, fail-closed handling, and step summary are the same in both modes, and one allowlist file serves both. The printed result and the step summary heading name the audited scope (`production dependencies` or `all dependencies`), so two runs in one workflow can be told apart.
|
|
24
|
+
|
|
25
|
+
An allowlist entry for an advisory that only exists in a dev dependency is reported as stale in a production-only run, because that run never sees the advisory. Treat the stale warning as expected when you run both scopes from one allowlist.
|
|
26
|
+
|
|
22
27
|
The gate fails closed: empty output, an audit error (registry down), or an unrecognized JSON shape fails instead of passing, an advisory it cannot identify is never allowlisted, and any severity other than info, low, or moderate blocks.
|
|
23
28
|
|
|
24
29
|
When `GITHUB_STEP_SUMMARY` is set, it appends a severity table, the allowlisted advisories, and any stale allowlist entries.
|
|
@@ -41,9 +46,31 @@ By default the gate reads `audit-allowlist.json` in the working directory. The f
|
|
|
41
46
|
- `reason` says why it is accepted, so a reviewer can judge it.
|
|
42
47
|
- `expires` is a `YYYY-MM-DD` date (UTC). On that date the entry fails the gate until someone re-reviews it and moves the date. An expired entry fails even if it matches nothing.
|
|
43
48
|
- `package` (optional, but never blank) limits the entry to the advisory in that package. Without it the entry covers the advisory in every package.
|
|
49
|
+
- `buildTimeOnly` (optional, `true` or `false`) records that the package never ships in the built server output. It needs `package` and does not change what the gate allows; `np-check-absent-dependency` reads it to verify the claim.
|
|
44
50
|
|
|
45
51
|
Unknown fields are rejected, so a typo cannot widen an entry. An entry that no longer matches any high or critical advisory is reported as stale. It does not fail the gate, but you should remove it.
|
|
46
52
|
|
|
53
|
+
## `np-check-absent-dependency`
|
|
54
|
+
|
|
55
|
+
Fails when a package appears in a build output directory. It backs the claim that an allowlisted advisory is build-time only: the audit gate accepts it, and this check proves the package did not reach the output.
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
pnpm exec np-check-absent-dependency .output/server vite
|
|
59
|
+
pnpm exec np-check-absent-dependency .output --from-allowlist
|
|
60
|
+
pnpm exec np-check-absent-dependency .output --allowlist path/to/audit-allowlist.json other-package
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The first argument is the output directory, followed by any number of package names (scoped names such as `@scope/name` work). `--from-allowlist` adds the `package` of every entry marked `"buildTimeOnly": true` in `audit-allowlist.json`, and `--allowlist <path>` does the same from another file (which must exist). An allowlist with no such entries checks nothing and passes; no names and no allowlist flag is a usage error, so a wrong invocation cannot pass silently. Names are checked against npm's naming rules.
|
|
64
|
+
|
|
65
|
+
A bundled copy has no `node_modules/<name>` path, so each file is checked for these signals, and the first hit per package is reported with its file:
|
|
66
|
+
|
|
67
|
+
- **node_modules path:** a file or directory whose path has a `node_modules/<name>` segment (including pnpm's nested `.pnpm/<name>@x/node_modules/<name>`).
|
|
68
|
+
- **package.json name:** a `package.json` whose `name` is exactly the package, wherever it was copied.
|
|
69
|
+
- **node_modules reference:** text containing `node_modules/<name>/`, which bundlers leave in region comments, source maps, and error stacks.
|
|
70
|
+
- **import specifier:** `from "<name>"`, `import("<name>")`, `import "<name>"`, or `require("<name>")`, with or without a subpath, which means the output loads the package at runtime.
|
|
71
|
+
|
|
72
|
+
Every signal needs the name followed by a delimiter, so `vite` does not match `vite-plugin-x` or `@scope/vite`. A minified, renamed bundle that keeps none of these markers can still hide a copy, so build with the bundler's module-path comments or source maps kept in the checked directory if you rely on this. A string such as `from "vite"` inside prose or a code sample also counts, and so does a type-only `import type ... from "vite"` quoted in a source map's `sourcesContent`. Files are read as UTF-8, and a file with a NUL byte in its first 8000 characters is treated as binary and not scanned. Symlinks are followed, and a dangling one fails the check. It fails if the directory is missing or empty.
|
|
73
|
+
|
|
47
74
|
## `np-check-action-pinning`
|
|
48
75
|
|
|
49
76
|
Fails when a `uses:` in `.github/workflows/*.yml`, `.github/actions/**/action.yml`, or a root `action.yml` is not pinned to a full 40-character commit SHA, or has no trailing version comment such as `# v4.1.0`. Local references (`./...`) are exempt. A `docker://` reference must be pinned to a `@sha256:` digest.
|
|
@@ -70,8 +97,13 @@ Environment variables, all passed by the workflow:
|
|
|
70
97
|
|
|
71
98
|
- `CURRENT_SHA`: the commit on `main` to compare against the live deploy.
|
|
72
99
|
- `NETLIFY_SITE_ID` and `NETLIFY_AUTH_TOKEN`: the site and a Netlify personal access token that can read it.
|
|
100
|
+
- `GITHUB_EVENT_NAME`: set by GitHub on every step. Inside a reusable workflow it holds the caller's event, so no input is needed.
|
|
101
|
+
|
|
102
|
+
A manual run (`GITHUB_EVENT_NAME` of `workflow_dispatch`) always deploys: it writes `skip=false`, prints that a manual run always deploys, and never calls Netlify. This covers a rebuild after a Netlify environment variable change, which does not change the commit. Every other event, and an unset `GITHUB_EVENT_NAME`, is decided as described below. In `production-deploy-decide.yml` the `require-ci-workflow` check still runs on a manual run, because a manual run forces the deploy decision, not the CI gate. Requires a `scripts-version` that includes this change; older versions still skip a manual run when the commit is already live.
|
|
103
|
+
|
|
104
|
+
The live commit is the one the site's published deploy was built from (`published_deploy.commit_ref` from `GET /sites/{id}`), so a manual rollback or locked auto-publishing is compared against what visitors are served, not the newest ready deploy.
|
|
73
105
|
|
|
74
|
-
Every uncertain case deploys: a missing variable, a Netlify lookup error, or no
|
|
106
|
+
Every uncertain case deploys: a missing variable, a Netlify lookup error, or no published deploy with a recorded commit all give `skip=false`, because a redundant deploy is cheap and a silently skipped one leaves a commit unshipped. It exits 0 either way; it only fails on a usage error such as an unknown flag, or when `GITHUB_OUTPUT` cannot be written.
|
|
75
107
|
|
|
76
108
|
## `np-verify-netlify-deploy`
|
|
77
109
|
|
|
@@ -87,7 +119,7 @@ Environment variables, all passed by the workflow:
|
|
|
87
119
|
- `NETLIFY_SITE_ID` and `NETLIFY_AUTH_TOKEN`: the site and a Netlify personal access token that can read it.
|
|
88
120
|
- `NETLIFY_TRIGGER_TITLE` and `NETLIFY_TRIGGERED_AT`: the title sent to the hook and when it was called (ISO 8601). Make the title unique per run (for example include the run id), because a deploy with the same title created up to two minutes earlier would be matched first. A deploy created up to two minutes before that time still counts, to absorb clock skew.
|
|
89
121
|
- `EXPECTED_COMMIT_SHA` (optional): the commit that was checked before triggering. The hook builds whatever `main` is when Netlify picks the job up, so a `ready` deploy of any other commit, or one with no recorded commit, fails.
|
|
90
|
-
- `NETLIFY_VERIFY_DEPLOY_ID` (optional): verify one known deploy (24 lowercase hex characters) instead of searching by title. The trigger variables are then not needed. The deploy must belong to `NETLIFY_SITE_ID` and be a production deploy.
|
|
122
|
+
- `NETLIFY_VERIFY_DEPLOY_ID` (optional): verify one known deploy (24 lowercase hex characters) instead of searching by title. The trigger variables are then not needed. The deploy must belong to `NETLIFY_SITE_ID` and be a production deploy. `NETLIFY_SITE_ID` may be the site UUID, the site name, or a domain, the same as when searching by title; when it differs from the deploy's site UUID it is resolved to the UUID with one extra API call (made once per run), and a site that cannot be found fails immediately.
|
|
91
123
|
|
|
92
124
|
| Flag | Default | Meaning |
|
|
93
125
|
| -------------------- | ------- | ----------------------- |
|
|
@@ -95,3 +127,90 @@ Environment variables, all passed by the workflow:
|
|
|
95
127
|
| `--interval-seconds` | `15` | Wait between polls |
|
|
96
128
|
|
|
97
129
|
`error`, `cancelled`, `rejected`, and `skipped` deploys fail immediately. Transient API errors (5xx, network) are retried until the timeout, and one last poll always runs at the deadline. Both flags take whole seconds from 1 to 21600. A rejected token or an unknown site id fails immediately.
|
|
130
|
+
|
|
131
|
+
## `np-check-migration-drift`
|
|
132
|
+
|
|
133
|
+
Run before `drizzle-kit migrate`. Compares the migrations recorded in the database (`drizzle.__drizzle_migrations`) with the journal and refuses to migrate when drizzle would re-run applied DDL or skip a migration forever. drizzle chooses what to run by a timestamp watermark and never compares hashes, so an edited journal `when` or an out-of-order migration is invisible until a deploy fails.
|
|
134
|
+
|
|
135
|
+
```sh
|
|
136
|
+
pnpm exec np-check-migration-drift
|
|
137
|
+
pnpm exec np-check-migration-drift --migrations-dir server/db/migrations --database-url-variable DATABASE_URL_UNPOOLED
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
- Reports `unknown-hash` (a recorded migration is not in the journal), `timestamp-drift` (a journal timestamp was raised above the watermark after the migration ran), and `silently-skipped` (an unapplied migration sits at or below the watermark). A journal timestamp lowered below the watermark is harmless and not reported.
|
|
141
|
+
- A database with no `drizzle.__drizzle_migrations` table yet is not drift; it passes.
|
|
142
|
+
- The migrations directory comes from `--migrations-dir`, then the `MIGRATIONS_DIR` variable, then `server/db/migrations`.
|
|
143
|
+
- The database URL is read from an environment variable only (`DATABASE_URL` unless `--database-url-variable` names another), never from an argument, and is never printed, not even in errors.
|
|
144
|
+
- It queries over Neon's SQL-over-HTTP endpoint, so it needs a Neon connection string and no database driver. Migration hashes are computed the way drizzle computes them (sha256 of each `.sql` file).
|
|
145
|
+
|
|
146
|
+
## `np-check-migration-snapshots`
|
|
147
|
+
|
|
148
|
+
Fails when a drizzle journal entry has no `<NNNN>_snapshot.json` in `meta/`, a snapshot has no journal entry, or a snapshot's `prevId` does not match the id of the snapshot before it (the first must use drizzle's all-zero root id). Any of these makes the next `drizzle-kit generate` diff against a stale base schema.
|
|
149
|
+
|
|
150
|
+
```sh
|
|
151
|
+
pnpm exec np-check-migration-snapshots
|
|
152
|
+
pnpm exec np-check-migration-snapshots --migrations-dir server/db/migrations
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The migrations directory is resolved as for `np-check-migration-drift`. A journal whose `idx` does not match its tag's `NNNN_` prefix, with duplicate `idx` values, or with no entries also fails, so both migration bins expect drizzle-kit's default `index` migration prefix.
|
|
156
|
+
|
|
157
|
+
## `np-report-lighthouse-failure`
|
|
158
|
+
|
|
159
|
+
Files a GitHub issue for a failed scheduled Lighthouse run, from a report job that runs after the audit. It reads Lighthouse CI's `.lighthouseci/assertion-results.json` and opens one issue per failing site (grouped by page host), titled `Lighthouse regression on <host>`, labeled `lighthouse-regression` and `p1` (created if missing). If the site already has an open issue it comments on it instead. After a passing run, `--passed` closes every open regression issue.
|
|
160
|
+
|
|
161
|
+
```sh
|
|
162
|
+
pnpm exec np-report-lighthouse-failure
|
|
163
|
+
pnpm exec np-report-lighthouse-failure --passed
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Environment variables, all passed by the workflow:
|
|
167
|
+
|
|
168
|
+
- `GH_TOKEN`: a token that can manage issues and labels (the `gh` CLI reads it). `gh` must be on the PATH, as it is on GitHub-hosted runners.
|
|
169
|
+
- `GITHUB_REPOSITORY`: set by GitHub Actions.
|
|
170
|
+
- `RUN_URL` and `HEAD_SHA`: the failed run's URL and commit (required unless `--passed`).
|
|
171
|
+
- `BUILD_OUTCOME` (optional): the build step's outcome (`success`, `failure`, `cancelled`, `skipped`), used to say which step failed.
|
|
172
|
+
|
|
173
|
+
| Flag | Default | Meaning |
|
|
174
|
+
| ------------ | -------------------------------------- | ---------------------------------------------------------------- |
|
|
175
|
+
| `--passed` | | Close open regression issues instead of filing one |
|
|
176
|
+
| `--results` | `.lighthouseci/assertion-results.json` | Lighthouse CI assertion results |
|
|
177
|
+
| `--workflow` | `lighthouse.yml` | Workflow file, to link the commits since its last passing run |
|
|
178
|
+
| `--site` | the repository name | Site named when the run failed before any assertion was recorded |
|
|
179
|
+
|
|
180
|
+
A run that failed before assertions were recorded (a failed build) still files one issue, under the `--site` name. The issue links the commit range since the last successful scheduled run of the workflow.
|
|
181
|
+
|
|
182
|
+
## `np-sync-templates`
|
|
183
|
+
|
|
184
|
+
Copies the files a package cannot export (husky hooks, Dependabot config, the base gitleaks config, and the pinned Node version) into the current repository, so they stop drifting between apps.
|
|
185
|
+
|
|
186
|
+
```sh
|
|
187
|
+
pnpm exec np-sync-templates --stack nuxt
|
|
188
|
+
pnpm exec np-sync-templates --stack nuxt --check
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Run it from the repository root. `--stack` is required and is `nuxt`, `vitepress`, or `node`. With `--check` nothing is written: it prints a diff for every file that differs (`-` is the repository's line, `+` the template's) and exits 1, so CI can fail on drift.
|
|
192
|
+
|
|
193
|
+
The Dependabot config groups every `@neon-pixels/*` update, of any kind, into its own pull request. The `neon-pixels` group is listed first among the npm groups because Dependabot puts a dependency in the first group that matches it; placed after `minor-and-patch`, it would never receive minor or patch bumps.
|
|
194
|
+
|
|
195
|
+
It touches only these files, and refuses any path that is a symlink or resolves outside the current directory:
|
|
196
|
+
|
|
197
|
+
| File | Variants |
|
|
198
|
+
| ------------------------ | ------------------------------------------------------------ |
|
|
199
|
+
| `.nvmrc` | none |
|
|
200
|
+
| `.gitleaks.toml` | none |
|
|
201
|
+
| `.github/dependabot.yml` | `vitepress` adds the vite and vitepress groups |
|
|
202
|
+
| `.husky/pre-commit` | none |
|
|
203
|
+
| `.husky/pre-push` | `nuxt` runs `nuxt prepare` and `lint:ci` |
|
|
204
|
+
| `.husky/post-merge` | none |
|
|
205
|
+
| `package.json` `engines` | none; sets `engines.node` and leaves every other field alone |
|
|
206
|
+
|
|
207
|
+
`engines.node` is a range that accepts the version pinned in `.nvmrc`. The Node 22 floor is 22.18.0 because Node runs TypeScript files directly (`node file.ts`) without a flag from that release, and synced projects run `.ts` scripts that way. Odd-numbered releases (Node 23 and 25) are left out on purpose, since they are short-lived and never reach long-term support; the open-ended `>=26.0.0` keeps later majors working without a template change. Tooling that checks `engines` can reject an unsupported Node version (npm and pnpm only warn unless `engine-strict=true` is set in `.npmrc`, which this sync does not manage). The hooks assume npm; the pre-push hooks run `lint`, `typecheck`, and `test:ci` scripts.
|
|
208
|
+
|
|
209
|
+
### Repo-specific sections
|
|
210
|
+
|
|
211
|
+
Lines between `# np-sync:begin <name>` and `# np-sync:end <name>` are kept when the file is synced, and everything else is overwritten. A file that has no markers yet is overwritten whole, so run `--check` and move any lines you want to keep into a section before the first sync. A section the repository does not have yet starts empty from the template. The synced files offer:
|
|
212
|
+
|
|
213
|
+
- `.gitleaks.toml`: `extra-rules` (more `[[rules]]`) and `allowlist` (more keys for the `[allowlist]` table, such as `commits` or `regexes`; do not repeat `paths`).
|
|
214
|
+
- `.husky/pre-commit` and `.husky/pre-push`: `repo-specific`, for extra steps before the shared ones.
|
|
215
|
+
|
|
216
|
+
Broken markers (unclosed, nested, duplicated, or unmatched) and sections with content that the template does not know stop the sync with an error before anything is written, so lines inside a section are never dropped.
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// src/audit-gate/report.ts
|
|
2
|
+
const NON_BLOCKING_SEVERITIES = /* @__PURE__ */ new Set([
|
|
3
|
+
"info",
|
|
4
|
+
"low",
|
|
5
|
+
"moderate"
|
|
6
|
+
]);
|
|
7
|
+
const UNIDENTIFIED_ADVISORY_ID = "UNIDENTIFIED";
|
|
8
|
+
const ADVISORY_ID_PATTERN = /GHSA(?:-[0-9a-z]{4}){3}/i;
|
|
9
|
+
function isObject$1(value) {
|
|
10
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11
|
+
}
|
|
12
|
+
function readString(value, fallback) {
|
|
13
|
+
return typeof value === "string" && value !== "" ? value : fallback;
|
|
14
|
+
}
|
|
15
|
+
function advisoryIdFromUrl(url) {
|
|
16
|
+
if (typeof url !== "string") return null;
|
|
17
|
+
const githubId = ADVISORY_ID_PATTERN.exec(url)?.[0];
|
|
18
|
+
if (githubId) return githubId;
|
|
19
|
+
return url.split("/").pop() || null;
|
|
20
|
+
}
|
|
21
|
+
function advisoryId(source) {
|
|
22
|
+
const githubId = source["github_advisory_id"];
|
|
23
|
+
if (typeof githubId === "string" && githubId !== "") return githubId;
|
|
24
|
+
const fromUrl = advisoryIdFromUrl(source["url"]);
|
|
25
|
+
if (fromUrl) return fromUrl;
|
|
26
|
+
const sourceNumber = source["source"] ?? source["id"];
|
|
27
|
+
if (typeof sourceNumber === "number" || typeof sourceNumber === "string") return `source-${sourceNumber}`;
|
|
28
|
+
return UNIDENTIFIED_ADVISORY_ID;
|
|
29
|
+
}
|
|
30
|
+
function toAdvisory(source, packageName) {
|
|
31
|
+
return {
|
|
32
|
+
id: advisoryId(source),
|
|
33
|
+
severity: readString(source["severity"], "unknown").toLowerCase(),
|
|
34
|
+
packageName: readString(packageName, "unknown"),
|
|
35
|
+
title: readString(source["title"], "no title")
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function advisoriesFromNpmReport(vulnerabilities) {
|
|
39
|
+
return Object.values(vulnerabilities).filter(isObject$1).flatMap((vulnerability) => Array.isArray(vulnerability["via"]) ? vulnerability["via"] : []).filter(isObject$1).map((via) => toAdvisory(via, via["name"]));
|
|
40
|
+
}
|
|
41
|
+
function advisoriesFromPnpmReport(advisories) {
|
|
42
|
+
return Object.values(advisories).filter(isObject$1).map((advisory) => toAdvisory(advisory, advisory["module_name"]));
|
|
43
|
+
}
|
|
44
|
+
function dedupe(advisories) {
|
|
45
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
46
|
+
for (const advisory of advisories) byKey.set(`${advisory.id}::${advisory.packageName}::${advisory.severity}`, advisory);
|
|
47
|
+
return [...byKey.values()];
|
|
48
|
+
}
|
|
49
|
+
function readAuditError(report) {
|
|
50
|
+
const error = report["error"];
|
|
51
|
+
if (!error) return null;
|
|
52
|
+
if (!isObject$1(error)) return "unknown error";
|
|
53
|
+
return readString(error["summary"], readString(error["message"], readString(error["code"], "unknown error")));
|
|
54
|
+
}
|
|
55
|
+
function collectAdvisories(report) {
|
|
56
|
+
if (isObject$1(report["vulnerabilities"])) return advisoriesFromNpmReport(report["vulnerabilities"]);
|
|
57
|
+
if (isObject$1(report["advisories"])) return advisoriesFromPnpmReport(report["advisories"]);
|
|
58
|
+
throw new Error("unrecognized audit JSON (no `vulnerabilities` or `advisories` map), refusing to pass");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Reads `npm audit --json` or `pnpm audit --json` output into distinct
|
|
62
|
+
* advisories. A broken audit (empty output, an error object, an unknown
|
|
63
|
+
* shape) throws, because it must never be mistaken for a clean report.
|
|
64
|
+
*/
|
|
65
|
+
function parseAuditReport(rawJson) {
|
|
66
|
+
if (rawJson.trim() === "") throw new Error("the audit produced no output");
|
|
67
|
+
let report;
|
|
68
|
+
try {
|
|
69
|
+
report = JSON.parse(rawJson);
|
|
70
|
+
} catch {
|
|
71
|
+
throw new Error("the audit output is not valid JSON");
|
|
72
|
+
}
|
|
73
|
+
if (!isObject$1(report)) throw new Error("the audit output is not a JSON object");
|
|
74
|
+
const auditError = readAuditError(report);
|
|
75
|
+
if (auditError) throw new Error(`the audit failed: ${auditError}`);
|
|
76
|
+
return dedupe(collectAdvisories(report));
|
|
77
|
+
}
|
|
78
|
+
function isBlocking(advisory) {
|
|
79
|
+
return !NON_BLOCKING_SEVERITIES.has(advisory.severity);
|
|
80
|
+
}
|
|
81
|
+
// src/audit-gate/allowlist.ts
|
|
82
|
+
const ENTRY_FIELDS = /* @__PURE__ */ new Set([
|
|
83
|
+
"id",
|
|
84
|
+
"reason",
|
|
85
|
+
"expires",
|
|
86
|
+
"package",
|
|
87
|
+
"buildTimeOnly"
|
|
88
|
+
]);
|
|
89
|
+
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
90
|
+
function isObject(value) {
|
|
91
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
92
|
+
}
|
|
93
|
+
function readRequiredText(entry, field, position) {
|
|
94
|
+
const value = entry[field];
|
|
95
|
+
if (typeof value !== "string" || value.trim() === "") throw new Error(`allowlist entry ${position} needs a non-empty "${field}" string`);
|
|
96
|
+
return value.trim();
|
|
97
|
+
}
|
|
98
|
+
function assertCalendarDate(date, position) {
|
|
99
|
+
const parsed = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
|
|
100
|
+
if (!(DATE_PATTERN.test(date) && !Number.isNaN(parsed.getTime()) && parsed.toISOString().startsWith(date))) throw new Error(`allowlist entry ${position} has an invalid "expires" date "${date}", expected YYYY-MM-DD`);
|
|
101
|
+
}
|
|
102
|
+
function assertKnownFields(entry, position) {
|
|
103
|
+
const unknownField = Object.keys(entry).find((field) => !ENTRY_FIELDS.has(field));
|
|
104
|
+
if (unknownField) throw new Error(`allowlist entry ${position} has an unknown field "${unknownField}"`);
|
|
105
|
+
}
|
|
106
|
+
function readBuildTimeOnly(entry, position) {
|
|
107
|
+
if (!("buildTimeOnly" in entry)) return {};
|
|
108
|
+
if (typeof entry["buildTimeOnly"] !== "boolean") throw new Error(`allowlist entry ${position} needs a boolean "buildTimeOnly"`);
|
|
109
|
+
if (!("package" in entry)) throw new Error(`allowlist entry ${position} sets "buildTimeOnly" without a "package" to check for`);
|
|
110
|
+
return { buildTimeOnly: entry["buildTimeOnly"] };
|
|
111
|
+
}
|
|
112
|
+
function parseEntry(entry, index) {
|
|
113
|
+
const position = index + 1;
|
|
114
|
+
if (!isObject(entry)) throw new Error(`allowlist entry ${position} is not an object`);
|
|
115
|
+
assertKnownFields(entry, position);
|
|
116
|
+
const expires = readRequiredText(entry, "expires", position);
|
|
117
|
+
assertCalendarDate(expires, position);
|
|
118
|
+
return {
|
|
119
|
+
id: readRequiredText(entry, "id", position),
|
|
120
|
+
reason: readRequiredText(entry, "reason", position),
|
|
121
|
+
expires,
|
|
122
|
+
..."package" in entry ? { package: readRequiredText(entry, "package", position) } : {},
|
|
123
|
+
...readBuildTimeOnly(entry, position)
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/** Parses the allowlist file: a JSON array of `{ id, reason, expires }`. */
|
|
127
|
+
function parseAllowlist(rawJson) {
|
|
128
|
+
let entries;
|
|
129
|
+
try {
|
|
130
|
+
entries = JSON.parse(rawJson);
|
|
131
|
+
} catch {
|
|
132
|
+
throw new Error("the allowlist is not valid JSON");
|
|
133
|
+
}
|
|
134
|
+
if (!Array.isArray(entries)) throw new Error("the allowlist must be a JSON array of entries");
|
|
135
|
+
return entries.map(parseEntry);
|
|
136
|
+
}
|
|
137
|
+
function isExpired(entry, now) {
|
|
138
|
+
return now >= /* @__PURE__ */ new Date(`${entry.expires}T00:00:00Z`);
|
|
139
|
+
}
|
|
140
|
+
function entryCovers(entry, advisory) {
|
|
141
|
+
if (advisory.id === "UNIDENTIFIED") return false;
|
|
142
|
+
const sameId = entry.id.toLowerCase() === advisory.id.toLowerCase();
|
|
143
|
+
const samePackage = entry.package === void 0 || entry.package === advisory.packageName;
|
|
144
|
+
return sameId && samePackage;
|
|
145
|
+
}
|
|
146
|
+
/** Package names of the entries marked build-time only, sorted, without duplicates. */
|
|
147
|
+
function buildTimeOnlyPackages(entries) {
|
|
148
|
+
const names = entries.flatMap((entry) => entry.buildTimeOnly === true && entry.package !== void 0 ? [entry.package] : []);
|
|
149
|
+
return [...new Set(names)].sort();
|
|
150
|
+
}
|
|
151
|
+
export { isBlocking as a, parseAllowlist as i, entryCovers as n, parseAuditReport as o, isExpired as r, buildTimeOnlyPackages as t };
|
package/dist/audit-gate.js
CHANGED
|
@@ -2,143 +2,39 @@
|
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import { appendFileSync, existsSync, readFileSync, readdirSync } from "node:fs";
|
|
4
4
|
import { parseArgs } from "node:util";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
"
|
|
9
|
-
"
|
|
10
|
-
]
|
|
11
|
-
const UNIDENTIFIED_ADVISORY_ID = "UNIDENTIFIED";
|
|
12
|
-
const ADVISORY_ID_PATTERN = /GHSA(?:-[0-9a-z]{4}){3}/i;
|
|
13
|
-
function isObject$1(value) {
|
|
14
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
15
|
-
}
|
|
16
|
-
function readString(value, fallback) {
|
|
17
|
-
return typeof value === "string" && value !== "" ? value : fallback;
|
|
18
|
-
}
|
|
19
|
-
function advisoryIdFromUrl(url) {
|
|
20
|
-
if (typeof url !== "string") return null;
|
|
21
|
-
const githubId = ADVISORY_ID_PATTERN.exec(url)?.[0];
|
|
22
|
-
if (githubId) return githubId;
|
|
23
|
-
return url.split("/").pop() || null;
|
|
24
|
-
}
|
|
25
|
-
function advisoryId(source) {
|
|
26
|
-
const githubId = source["github_advisory_id"];
|
|
27
|
-
if (typeof githubId === "string" && githubId !== "") return githubId;
|
|
28
|
-
const fromUrl = advisoryIdFromUrl(source["url"]);
|
|
29
|
-
if (fromUrl) return fromUrl;
|
|
30
|
-
const sourceNumber = source["source"] ?? source["id"];
|
|
31
|
-
if (typeof sourceNumber === "number" || typeof sourceNumber === "string") return `source-${sourceNumber}`;
|
|
32
|
-
return UNIDENTIFIED_ADVISORY_ID;
|
|
33
|
-
}
|
|
34
|
-
function toAdvisory(source, packageName) {
|
|
35
|
-
return {
|
|
36
|
-
id: advisoryId(source),
|
|
37
|
-
severity: readString(source["severity"], "unknown").toLowerCase(),
|
|
38
|
-
packageName: readString(packageName, "unknown"),
|
|
39
|
-
title: readString(source["title"], "no title")
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
function advisoriesFromNpmReport(vulnerabilities) {
|
|
43
|
-
return Object.values(vulnerabilities).filter(isObject$1).flatMap((vulnerability) => Array.isArray(vulnerability["via"]) ? vulnerability["via"] : []).filter(isObject$1).map((via) => toAdvisory(via, via["name"]));
|
|
44
|
-
}
|
|
45
|
-
function advisoriesFromPnpmReport(advisories) {
|
|
46
|
-
return Object.values(advisories).filter(isObject$1).map((advisory) => toAdvisory(advisory, advisory["module_name"]));
|
|
47
|
-
}
|
|
48
|
-
function dedupe(advisories) {
|
|
49
|
-
const byKey = /* @__PURE__ */ new Map();
|
|
50
|
-
for (const advisory of advisories) byKey.set(`${advisory.id}::${advisory.packageName}::${advisory.severity}`, advisory);
|
|
51
|
-
return [...byKey.values()];
|
|
52
|
-
}
|
|
53
|
-
function readAuditError(report) {
|
|
54
|
-
const error = report["error"];
|
|
55
|
-
if (!error) return null;
|
|
56
|
-
if (!isObject$1(error)) return "unknown error";
|
|
57
|
-
return readString(error["summary"], readString(error["message"], readString(error["code"], "unknown error")));
|
|
58
|
-
}
|
|
59
|
-
function collectAdvisories(report) {
|
|
60
|
-
if (isObject$1(report["vulnerabilities"])) return advisoriesFromNpmReport(report["vulnerabilities"]);
|
|
61
|
-
if (isObject$1(report["advisories"])) return advisoriesFromPnpmReport(report["advisories"]);
|
|
62
|
-
throw new Error("unrecognized audit JSON (no `vulnerabilities` or `advisories` map), refusing to pass");
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Reads `npm audit --json` or `pnpm audit --json` output into distinct
|
|
66
|
-
* advisories. A broken audit (empty output, an error object, an unknown
|
|
67
|
-
* shape) throws, because it must never be mistaken for a clean report.
|
|
68
|
-
*/
|
|
69
|
-
function parseAuditReport(rawJson) {
|
|
70
|
-
if (rawJson.trim() === "") throw new Error("the audit produced no output");
|
|
71
|
-
let report;
|
|
72
|
-
try {
|
|
73
|
-
report = JSON.parse(rawJson);
|
|
74
|
-
} catch {
|
|
75
|
-
throw new Error("the audit output is not valid JSON");
|
|
76
|
-
}
|
|
77
|
-
if (!isObject$1(report)) throw new Error("the audit output is not a JSON object");
|
|
78
|
-
const auditError = readAuditError(report);
|
|
79
|
-
if (auditError) throw new Error(`the audit failed: ${auditError}`);
|
|
80
|
-
return dedupe(collectAdvisories(report));
|
|
81
|
-
}
|
|
82
|
-
function isBlocking(advisory) {
|
|
83
|
-
return !NON_BLOCKING_SEVERITIES.has(advisory.severity);
|
|
84
|
-
}
|
|
85
|
-
// src/audit-gate/allowlist.ts
|
|
86
|
-
const ENTRY_FIELDS = /* @__PURE__ */ new Set([
|
|
87
|
-
"id",
|
|
88
|
-
"reason",
|
|
89
|
-
"expires",
|
|
90
|
-
"package"
|
|
5
|
+
import { a as isBlocking, i as parseAllowlist, n as entryCovers, o as parseAuditReport, r as isExpired } from "./allowlist-B_zgqKrH.js";
|
|
6
|
+
// src/audit-gate/package-manager.ts
|
|
7
|
+
const LOCKFILES = /* @__PURE__ */ new Map([
|
|
8
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
9
|
+
["package-lock.json", "npm"],
|
|
10
|
+
["npm-shrinkwrap.json", "npm"]
|
|
91
11
|
]);
|
|
92
|
-
|
|
93
|
-
function
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (typeof value !== "string" || value.trim() === "") throw new Error(`allowlist entry ${position} needs a non-empty "${field}" string`);
|
|
99
|
-
return value.trim();
|
|
100
|
-
}
|
|
101
|
-
function assertCalendarDate(date, position) {
|
|
102
|
-
const parsed = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
|
|
103
|
-
if (!(DATE_PATTERN.test(date) && !Number.isNaN(parsed.getTime()) && parsed.toISOString().startsWith(date))) throw new Error(`allowlist entry ${position} has an invalid "expires" date "${date}", expected YYYY-MM-DD`);
|
|
104
|
-
}
|
|
105
|
-
function assertKnownFields(entry, position) {
|
|
106
|
-
const unknownField = Object.keys(entry).find((field) => !ENTRY_FIELDS.has(field));
|
|
107
|
-
if (unknownField) throw new Error(`allowlist entry ${position} has an unknown field "${unknownField}"`);
|
|
12
|
+
/** Picks the package manager from the lockfiles present in the project. */
|
|
13
|
+
function detectPackageManager(fileNames) {
|
|
14
|
+
const found = new Set(fileNames.flatMap((name) => LOCKFILES.get(name) ?? []));
|
|
15
|
+
if (found.size === 0) throw new Error("no supported lockfile found (pnpm-lock.yaml, package-lock.json, npm-shrinkwrap.json)");
|
|
16
|
+
if (found.size > 1) throw new Error("both npm and pnpm lockfiles found, keep only one");
|
|
17
|
+
return [...found][0];
|
|
108
18
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
19
|
+
const SCOPE_LABELS = {
|
|
20
|
+
production: "production dependencies",
|
|
21
|
+
all: "all dependencies"
|
|
22
|
+
};
|
|
23
|
+
const PRODUCTION_FLAGS = {
|
|
24
|
+
pnpm: "--prod",
|
|
25
|
+
npm: "--omit=dev"
|
|
26
|
+
};
|
|
27
|
+
/** JSON output; the gate does its own severity filtering. */
|
|
28
|
+
function auditCommandFor(packageManager, scope = "production") {
|
|
115
29
|
return {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
30
|
+
command: packageManager,
|
|
31
|
+
args: [
|
|
32
|
+
"audit",
|
|
33
|
+
...scope === "production" ? [PRODUCTION_FLAGS[packageManager]] : [],
|
|
34
|
+
"--json"
|
|
35
|
+
]
|
|
120
36
|
};
|
|
121
37
|
}
|
|
122
|
-
/** Parses the allowlist file: a JSON array of `{ id, reason, expires }`. */
|
|
123
|
-
function parseAllowlist(rawJson) {
|
|
124
|
-
let entries;
|
|
125
|
-
try {
|
|
126
|
-
entries = JSON.parse(rawJson);
|
|
127
|
-
} catch {
|
|
128
|
-
throw new Error("the allowlist is not valid JSON");
|
|
129
|
-
}
|
|
130
|
-
if (!Array.isArray(entries)) throw new Error("the allowlist must be a JSON array of entries");
|
|
131
|
-
return entries.map(parseEntry);
|
|
132
|
-
}
|
|
133
|
-
function isExpired(entry, now) {
|
|
134
|
-
return now >= /* @__PURE__ */ new Date(`${entry.expires}T00:00:00Z`);
|
|
135
|
-
}
|
|
136
|
-
function entryCovers(entry, advisory) {
|
|
137
|
-
if (advisory.id === "UNIDENTIFIED") return false;
|
|
138
|
-
const sameId = entry.id.toLowerCase() === advisory.id.toLowerCase();
|
|
139
|
-
const samePackage = entry.package === void 0 || entry.package === advisory.packageName;
|
|
140
|
-
return sameId && samePackage;
|
|
141
|
-
}
|
|
142
38
|
// src/audit-gate/gate.ts
|
|
143
39
|
const REPORTED_SEVERITIES = [
|
|
144
40
|
"critical",
|
|
@@ -177,10 +73,10 @@ function otherSeverityRows(counts) {
|
|
|
177
73
|
return Object.entries(counts).filter(([severity]) => !REPORTED_SEVERITIES.includes(severity)).map(([severity, count]) => `| ${severity} | ${count} |`);
|
|
178
74
|
}
|
|
179
75
|
/** Markdown for the GitHub step summary. */
|
|
180
|
-
function formatSummary(result) {
|
|
76
|
+
function formatSummary(result, scope = "production") {
|
|
181
77
|
const { severityCounts } = result;
|
|
182
78
|
const lines = [
|
|
183
|
-
|
|
79
|
+
`## Dependency audit (${SCOPE_LABELS[scope]})`,
|
|
184
80
|
"",
|
|
185
81
|
"| Severity | Advisories |",
|
|
186
82
|
"| -------- | ---------- |",
|
|
@@ -204,46 +100,14 @@ function formatSummary(result) {
|
|
|
204
100
|
}
|
|
205
101
|
return `${lines.join("\n")}\n`;
|
|
206
102
|
}
|
|
207
|
-
// src/audit-gate/package-manager.ts
|
|
208
|
-
const LOCKFILES = /* @__PURE__ */ new Map([
|
|
209
|
-
["pnpm-lock.yaml", "pnpm"],
|
|
210
|
-
["package-lock.json", "npm"],
|
|
211
|
-
["npm-shrinkwrap.json", "npm"]
|
|
212
|
-
]);
|
|
213
|
-
/** Picks the package manager from the lockfiles present in the project. */
|
|
214
|
-
function detectPackageManager(fileNames) {
|
|
215
|
-
const found = new Set(fileNames.flatMap((name) => LOCKFILES.get(name) ?? []));
|
|
216
|
-
if (found.size === 0) throw new Error("no supported lockfile found (pnpm-lock.yaml, package-lock.json, npm-shrinkwrap.json)");
|
|
217
|
-
if (found.size > 1) throw new Error("both npm and pnpm lockfiles found, keep only one");
|
|
218
|
-
return [...found][0];
|
|
219
|
-
}
|
|
220
|
-
/** Production dependencies only, JSON output; the gate does its own filtering. */
|
|
221
|
-
function auditCommandFor(packageManager) {
|
|
222
|
-
if (packageManager === "pnpm") return {
|
|
223
|
-
command: "pnpm",
|
|
224
|
-
args: [
|
|
225
|
-
"audit",
|
|
226
|
-
"--prod",
|
|
227
|
-
"--json"
|
|
228
|
-
]
|
|
229
|
-
};
|
|
230
|
-
return {
|
|
231
|
-
command: "npm",
|
|
232
|
-
args: [
|
|
233
|
-
"audit",
|
|
234
|
-
"--omit=dev",
|
|
235
|
-
"--json"
|
|
236
|
-
]
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
103
|
const MAX_AUDIT_OUTPUT_BYTES = 67108864;
|
|
240
104
|
function readAuditOutput(command, result) {
|
|
241
105
|
if (result.error) throw new Error(`could not run ${command}: ${result.error.message}`);
|
|
242
106
|
if (result.stdout.trim() === "" && result.stderr.trim() !== "") throw new Error(`${command} audit failed: ${result.stderr.trim()}`);
|
|
243
107
|
return result.stdout;
|
|
244
108
|
}
|
|
245
|
-
function runAuditCommand(packageManager) {
|
|
246
|
-
const { command, args } = auditCommandFor(packageManager);
|
|
109
|
+
function runAuditCommand(packageManager, scope) {
|
|
110
|
+
const { command, args } = auditCommandFor(packageManager, scope);
|
|
247
111
|
return readAuditOutput(command, spawnSync(command, args, {
|
|
248
112
|
encoding: "utf-8",
|
|
249
113
|
maxBuffer: MAX_AUDIT_OUTPUT_BYTES
|
|
@@ -264,26 +128,37 @@ function loadAllowlist(environment, explicitPath) {
|
|
|
264
128
|
if (content === null && explicitPath !== void 0) throw new Error(`allowlist file not found: ${explicitPath}`);
|
|
265
129
|
return content === null ? [] : parseAllowlist(content);
|
|
266
130
|
}
|
|
267
|
-
function printResult(result) {
|
|
131
|
+
function printResult(result, scope) {
|
|
132
|
+
console.log(`np-audit-gate: audited ${SCOPE_LABELS[scope]}`);
|
|
268
133
|
for (const entry of result.staleEntries) console.warn(`np-audit-gate: stale allowlist entry ${entry.id}, remove it`);
|
|
269
134
|
for (const failure of result.failures) console.error(`np-audit-gate: ${failure}`);
|
|
270
|
-
if (result.failures.length === 0) console.log(
|
|
135
|
+
if (result.failures.length === 0) console.log(`np-audit-gate: no un-allowlisted high or critical advisories in ${SCOPE_LABELS[scope]}`);
|
|
271
136
|
}
|
|
272
137
|
function runGate(argv, environment) {
|
|
273
138
|
const { values } = parseArgs({
|
|
274
139
|
args: argv,
|
|
275
|
-
options: {
|
|
140
|
+
options: {
|
|
141
|
+
allowlist: { type: "string" },
|
|
142
|
+
"include-dev": {
|
|
143
|
+
type: "boolean",
|
|
144
|
+
default: false
|
|
145
|
+
}
|
|
146
|
+
}
|
|
276
147
|
});
|
|
148
|
+
const scope = values["include-dev"] ? "all" : "production";
|
|
277
149
|
const allowlist = loadAllowlist(environment, values.allowlist);
|
|
278
150
|
const packageManager = detectPackageManager(environment.listProjectFiles());
|
|
279
|
-
return
|
|
151
|
+
return {
|
|
152
|
+
result: evaluateAudit(parseAuditReport(environment.runAudit(packageManager, scope)), allowlist, environment.now()),
|
|
153
|
+
scope
|
|
154
|
+
};
|
|
280
155
|
}
|
|
281
156
|
/** Runs the gate and returns the process exit code. */
|
|
282
157
|
function runAuditGate(argv, environment = systemEnvironment) {
|
|
283
158
|
try {
|
|
284
|
-
const result = runGate(argv, environment);
|
|
285
|
-
printResult(result);
|
|
286
|
-
environment.appendStepSummary(formatSummary(result));
|
|
159
|
+
const { result, scope } = runGate(argv, environment);
|
|
160
|
+
printResult(result, scope);
|
|
161
|
+
environment.appendStepSummary(formatSummary(result, scope));
|
|
287
162
|
return result.failures.length > 0 ? 1 : 0;
|
|
288
163
|
} catch (error) {
|
|
289
164
|
const reason = error instanceof Error ? error.message : String(error);
|