@neon-pixels/scripts 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 +21 -0
- package/README.md +96 -2
- package/dist/audit-gate.js +296 -0
- package/dist/check-action-pinning.js +97 -0
- package/dist/should-deploy.js +82 -0
- package/dist/verify-netlify-deploy.js +224 -0
- package/dist/workflow-command-BkYMh3G8.js +76 -0
- package/package.json +31 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Neon Pixels Studio
|
|
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,97 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @neon-pixels/scripts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
CI and deploy scripts for Neon Pixels projects. They are command-line tools with no library API. The gates print one line per failure and exit non-zero; `np-should-deploy` fails only on a usage error or when it cannot write `GITHUB_OUTPUT` (see below). None prints environment variables or tokens.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add -D @neon-pixels/scripts
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## `np-audit-gate`
|
|
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.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
pnpm exec np-audit-gate
|
|
17
|
+
pnpm exec np-audit-gate --allowlist path/to/audit-allowlist.json
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
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
|
+
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
|
+
|
|
24
|
+
When `GITHUB_STEP_SUMMARY` is set, it appends a severity table, the allowlisted advisories, and any stale allowlist entries.
|
|
25
|
+
|
|
26
|
+
### Allowlist
|
|
27
|
+
|
|
28
|
+
By default the gate reads `audit-allowlist.json` in the working directory. The file is optional by default; with `--allowlist` it must exist. It is a JSON array, and every entry needs an advisory id, a reason, and an expiry date:
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
[
|
|
32
|
+
{
|
|
33
|
+
"id": "GHSA-xxxx-xxxx-xxxx",
|
|
34
|
+
"reason": "No patched release exists. Only reachable from build tooling.",
|
|
35
|
+
"expires": "2027-03-01"
|
|
36
|
+
}
|
|
37
|
+
]
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- `id` is the advisory id as the audit reports it (matched case-insensitively).
|
|
41
|
+
- `reason` says why it is accepted, so a reviewer can judge it.
|
|
42
|
+
- `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
|
+
- `package` (optional, but never blank) limits the entry to the advisory in that package. Without it the entry covers the advisory in every package.
|
|
44
|
+
|
|
45
|
+
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
|
+
|
|
47
|
+
## `np-check-action-pinning`
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
pnpm exec np-check-action-pinning
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Run it from the repository root. It fails if it finds no workflow files, so a wrong working directory cannot pass silently.
|
|
56
|
+
|
|
57
|
+
```yaml
|
|
58
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## `np-should-deploy`
|
|
62
|
+
|
|
63
|
+
Decides whether `main` has commits newer than the live Netlify production deploy, for a scheduled deploy workflow. It writes `skip=true` (the commit is already live) or `skip=false` to the file named by `GITHUB_OUTPUT`, and prints the reason.
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
pnpm exec np-should-deploy
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Environment variables, all passed by the workflow:
|
|
70
|
+
|
|
71
|
+
- `CURRENT_SHA`: the commit on `main` to compare against the live deploy.
|
|
72
|
+
- `NETLIFY_SITE_ID` and `NETLIFY_AUTH_TOKEN`: the site and a Netlify personal access token that can read it.
|
|
73
|
+
|
|
74
|
+
Every uncertain case deploys: a missing variable, a Netlify lookup error, or no successful production deploy on record 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
|
+
|
|
76
|
+
## `np-verify-netlify-deploy`
|
|
77
|
+
|
|
78
|
+
Waits for the production deploy a build hook started, and fails unless it reaches `ready` (and, when `EXPECTED_COMMIT_SHA` is set, was built from that commit). A hook answers with an empty body, so the deploy is found by the title the trigger step sent and the time it fired. Failure messages are written as `::error::` workflow annotations with Netlify's text escaped.
|
|
79
|
+
|
|
80
|
+
```sh
|
|
81
|
+
pnpm exec np-verify-netlify-deploy
|
|
82
|
+
pnpm exec np-verify-netlify-deploy --timeout-seconds 1800 --interval-seconds 30
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Environment variables, all passed by the workflow:
|
|
86
|
+
|
|
87
|
+
- `NETLIFY_SITE_ID` and `NETLIFY_AUTH_TOKEN`: the site and a Netlify personal access token that can read it.
|
|
88
|
+
- `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
|
+
- `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.
|
|
91
|
+
|
|
92
|
+
| Flag | Default | Meaning |
|
|
93
|
+
| -------------------- | ------- | ----------------------- |
|
|
94
|
+
| `--timeout-seconds` | `1200` | Give up after this long |
|
|
95
|
+
| `--interval-seconds` | `15` | Wait between polls |
|
|
96
|
+
|
|
97
|
+
`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.
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { appendFileSync, existsSync, readFileSync, readdirSync } from "node:fs";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
// src/audit-gate/report.ts
|
|
6
|
+
const NON_BLOCKING_SEVERITIES = /* @__PURE__ */ new Set([
|
|
7
|
+
"info",
|
|
8
|
+
"low",
|
|
9
|
+
"moderate"
|
|
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"
|
|
91
|
+
]);
|
|
92
|
+
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
93
|
+
function isObject(value) {
|
|
94
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
95
|
+
}
|
|
96
|
+
function readRequiredText(entry, field, position) {
|
|
97
|
+
const value = entry[field];
|
|
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}"`);
|
|
108
|
+
}
|
|
109
|
+
function parseEntry(entry, index) {
|
|
110
|
+
const position = index + 1;
|
|
111
|
+
if (!isObject(entry)) throw new Error(`allowlist entry ${position} is not an object`);
|
|
112
|
+
assertKnownFields(entry, position);
|
|
113
|
+
const expires = readRequiredText(entry, "expires", position);
|
|
114
|
+
assertCalendarDate(expires, position);
|
|
115
|
+
return {
|
|
116
|
+
id: readRequiredText(entry, "id", position),
|
|
117
|
+
reason: readRequiredText(entry, "reason", position),
|
|
118
|
+
expires,
|
|
119
|
+
..."package" in entry ? { package: readRequiredText(entry, "package", position) } : {}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
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
|
+
// src/audit-gate/gate.ts
|
|
143
|
+
const REPORTED_SEVERITIES = [
|
|
144
|
+
"critical",
|
|
145
|
+
"high",
|
|
146
|
+
"moderate",
|
|
147
|
+
"low"
|
|
148
|
+
];
|
|
149
|
+
function describeAdvisory(advisory) {
|
|
150
|
+
return `${advisory.id} [${advisory.severity}] ${advisory.packageName}`;
|
|
151
|
+
}
|
|
152
|
+
function countBySeverity(advisories) {
|
|
153
|
+
const counts = new Map(REPORTED_SEVERITIES.map((severity) => [severity, 0]));
|
|
154
|
+
for (const advisory of advisories) counts.set(advisory.severity, (counts.get(advisory.severity) ?? 0) + 1);
|
|
155
|
+
return Object.fromEntries(counts);
|
|
156
|
+
}
|
|
157
|
+
function expiredFailures(entries, now) {
|
|
158
|
+
return entries.filter((entry) => isExpired(entry, now)).map((entry) => `allowlist entry ${entry.id}${entry.package ? ` (${entry.package})` : ""} expired on ${entry.expires}, re-review it (reason was: ${entry.reason})`);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Decides pass or fail. An expired entry fails the gate by itself but still
|
|
162
|
+
* covers its advisory, so one problem produces one failure line.
|
|
163
|
+
*/
|
|
164
|
+
function evaluateAudit(advisories, allowlist, now) {
|
|
165
|
+
const blocking = advisories.filter(isBlocking);
|
|
166
|
+
const isCovered = (advisory) => allowlist.some((entry) => entryCovers(entry, advisory));
|
|
167
|
+
const unaccepted = blocking.filter((advisory) => !isCovered(advisory));
|
|
168
|
+
const staleEntries = allowlist.filter((entry) => !blocking.some((advisory) => entryCovers(entry, advisory)));
|
|
169
|
+
return {
|
|
170
|
+
failures: [...expiredFailures(allowlist, now), ...unaccepted.map((advisory) => `${describeAdvisory(advisory)} is not allowlisted: ${advisory.title}`)],
|
|
171
|
+
staleEntries,
|
|
172
|
+
accepted: blocking.filter(isCovered),
|
|
173
|
+
severityCounts: countBySeverity(advisories)
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function otherSeverityRows(counts) {
|
|
177
|
+
return Object.entries(counts).filter(([severity]) => !REPORTED_SEVERITIES.includes(severity)).map(([severity, count]) => `| ${severity} | ${count} |`);
|
|
178
|
+
}
|
|
179
|
+
/** Markdown for the GitHub step summary. */
|
|
180
|
+
function formatSummary(result) {
|
|
181
|
+
const { severityCounts } = result;
|
|
182
|
+
const lines = [
|
|
183
|
+
"## Dependency audit",
|
|
184
|
+
"",
|
|
185
|
+
"| Severity | Advisories |",
|
|
186
|
+
"| -------- | ---------- |",
|
|
187
|
+
`| Critical | ${severityCounts["critical"] ?? 0} |`,
|
|
188
|
+
`| High | ${severityCounts["high"] ?? 0} |`,
|
|
189
|
+
`| Moderate | ${severityCounts["moderate"] ?? 0} |`,
|
|
190
|
+
`| Low | ${severityCounts["low"] ?? 0} |`,
|
|
191
|
+
...otherSeverityRows(severityCounts)
|
|
192
|
+
];
|
|
193
|
+
if (result.accepted.length > 0) {
|
|
194
|
+
lines.push("", "Allowlisted high/critical advisories:");
|
|
195
|
+
lines.push(...result.accepted.map((advisory) => `- ${describeAdvisory(advisory)}`));
|
|
196
|
+
}
|
|
197
|
+
if (result.staleEntries.length > 0) {
|
|
198
|
+
lines.push("", "Stale allowlist entries (safe to remove):");
|
|
199
|
+
lines.push(...result.staleEntries.map((entry) => `- ${entry.id}`));
|
|
200
|
+
}
|
|
201
|
+
if (result.failures.length > 0) {
|
|
202
|
+
lines.push("", "Failures:");
|
|
203
|
+
lines.push(...result.failures.map((failure) => `- ${failure}`));
|
|
204
|
+
}
|
|
205
|
+
return `${lines.join("\n")}\n`;
|
|
206
|
+
}
|
|
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
|
+
const MAX_AUDIT_OUTPUT_BYTES = 67108864;
|
|
240
|
+
function readAuditOutput(command, result) {
|
|
241
|
+
if (result.error) throw new Error(`could not run ${command}: ${result.error.message}`);
|
|
242
|
+
if (result.stdout.trim() === "" && result.stderr.trim() !== "") throw new Error(`${command} audit failed: ${result.stderr.trim()}`);
|
|
243
|
+
return result.stdout;
|
|
244
|
+
}
|
|
245
|
+
function runAuditCommand(packageManager) {
|
|
246
|
+
const { command, args } = auditCommandFor(packageManager);
|
|
247
|
+
return readAuditOutput(command, spawnSync(command, args, {
|
|
248
|
+
encoding: "utf-8",
|
|
249
|
+
maxBuffer: MAX_AUDIT_OUTPUT_BYTES
|
|
250
|
+
}));
|
|
251
|
+
}
|
|
252
|
+
const systemEnvironment = {
|
|
253
|
+
listProjectFiles: () => readdirSync("."),
|
|
254
|
+
readTextFile: (path) => existsSync(path) ? readFileSync(path, "utf-8") : null,
|
|
255
|
+
runAudit: runAuditCommand,
|
|
256
|
+
now: () => /* @__PURE__ */ new Date(),
|
|
257
|
+
appendStepSummary: (markdown) => {
|
|
258
|
+
const summaryPath = process.env["GITHUB_STEP_SUMMARY"];
|
|
259
|
+
if (summaryPath) appendFileSync(summaryPath, markdown);
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
function loadAllowlist(environment, explicitPath) {
|
|
263
|
+
const content = environment.readTextFile(explicitPath ?? "audit-allowlist.json");
|
|
264
|
+
if (content === null && explicitPath !== void 0) throw new Error(`allowlist file not found: ${explicitPath}`);
|
|
265
|
+
return content === null ? [] : parseAllowlist(content);
|
|
266
|
+
}
|
|
267
|
+
function printResult(result) {
|
|
268
|
+
for (const entry of result.staleEntries) console.warn(`np-audit-gate: stale allowlist entry ${entry.id}, remove it`);
|
|
269
|
+
for (const failure of result.failures) console.error(`np-audit-gate: ${failure}`);
|
|
270
|
+
if (result.failures.length === 0) console.log("np-audit-gate: no un-allowlisted high or critical advisories");
|
|
271
|
+
}
|
|
272
|
+
function runGate(argv, environment) {
|
|
273
|
+
const { values } = parseArgs({
|
|
274
|
+
args: argv,
|
|
275
|
+
options: { allowlist: { type: "string" } }
|
|
276
|
+
});
|
|
277
|
+
const allowlist = loadAllowlist(environment, values.allowlist);
|
|
278
|
+
const packageManager = detectPackageManager(environment.listProjectFiles());
|
|
279
|
+
return evaluateAudit(parseAuditReport(environment.runAudit(packageManager)), allowlist, environment.now());
|
|
280
|
+
}
|
|
281
|
+
/** Runs the gate and returns the process exit code. */
|
|
282
|
+
function runAuditGate(argv, environment = systemEnvironment) {
|
|
283
|
+
try {
|
|
284
|
+
const result = runGate(argv, environment);
|
|
285
|
+
printResult(result);
|
|
286
|
+
environment.appendStepSummary(formatSummary(result));
|
|
287
|
+
return result.failures.length > 0 ? 1 : 0;
|
|
288
|
+
} catch (error) {
|
|
289
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
290
|
+
console.error(`np-audit-gate: ${reason}`);
|
|
291
|
+
return 1;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
// src/audit-gate.ts
|
|
295
|
+
process.exitCode = runAuditGate(process.argv.slice(2));
|
|
296
|
+
export {};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
import { join, relative } from "node:path";
|
|
4
|
+
// src/action-pinning/check.ts
|
|
5
|
+
const KEY_START = String.raw`(?:^\s*(?:-\s+)?|[{,]\s*)["']?uses["']?\s*:`;
|
|
6
|
+
const USES_PATTERN = new RegExp(String.raw`${KEY_START}\s*(?:'([^']*)'|"([^"]*)"|([^\s,}]+))(.*)$`);
|
|
7
|
+
const BARE_USES_PATTERN = new RegExp(String.raw`${KEY_START}\s*(?:#.*)?$`);
|
|
8
|
+
const COMMIT_REFERENCE_PATTERN = /^[^@\s]+@[0-9a-f]{40}$/;
|
|
9
|
+
const DOCKER_DIGEST_PATTERN = /^docker:\/\/\S+@sha256:[0-9a-f]{64}$/;
|
|
10
|
+
const VERSION_COMMENT_PATTERN = /#\s*v?\d/;
|
|
11
|
+
const DOCKER_PREFIX = "docker://";
|
|
12
|
+
function isLocalReference(reference) {
|
|
13
|
+
return reference.startsWith("./");
|
|
14
|
+
}
|
|
15
|
+
function isPinned(reference) {
|
|
16
|
+
if (reference.startsWith(DOCKER_PREFIX)) return DOCKER_DIGEST_PATTERN.test(reference);
|
|
17
|
+
return COMMIT_REFERENCE_PATTERN.test(reference);
|
|
18
|
+
}
|
|
19
|
+
function pinningProblem(reference, trailer) {
|
|
20
|
+
if (!isPinned(reference)) return reference.startsWith(DOCKER_PREFIX) ? "is not pinned to a @sha256 digest" : "is not pinned to a full commit SHA";
|
|
21
|
+
if (!VERSION_COMMENT_PATTERN.test(trailer)) return "has no trailing version comment (for example `# v4.1.0`)";
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
function violationForLine(file, text, index) {
|
|
25
|
+
if (BARE_USES_PATTERN.test(text)) return {
|
|
26
|
+
file,
|
|
27
|
+
line: index + 1,
|
|
28
|
+
reference: "uses:",
|
|
29
|
+
reason: "has its value on a following line, put it on the same line"
|
|
30
|
+
};
|
|
31
|
+
const match = USES_PATTERN.exec(text);
|
|
32
|
+
if (!match) return null;
|
|
33
|
+
const reference = match[1] ?? match[2] ?? match[3] ?? "";
|
|
34
|
+
if (reference === "" || isLocalReference(reference)) return null;
|
|
35
|
+
const reason = pinningProblem(reference, match[4] ?? "");
|
|
36
|
+
return reason ? {
|
|
37
|
+
file,
|
|
38
|
+
line: index + 1,
|
|
39
|
+
reference,
|
|
40
|
+
reason
|
|
41
|
+
} : null;
|
|
42
|
+
}
|
|
43
|
+
/** Finds every `uses:` in one workflow or composite action file that is not pinned. */
|
|
44
|
+
function findPinningViolations(file, content) {
|
|
45
|
+
return content.split(/\r?\n/).map((text, index) => violationForLine(file, text, index)).filter((violation) => violation !== null);
|
|
46
|
+
}
|
|
47
|
+
function formatViolation(violation) {
|
|
48
|
+
return `${violation.file}:${violation.line} ${violation.reference} ${violation.reason}`;
|
|
49
|
+
}
|
|
50
|
+
// src/action-pinning/run.ts
|
|
51
|
+
const WORKFLOWS_DIRECTORY = ".github/workflows";
|
|
52
|
+
const ACTIONS_DIRECTORY = ".github/actions";
|
|
53
|
+
const YAML_PATTERN = /\.ya?ml$/;
|
|
54
|
+
const ACTION_FILE_PATTERN = /^action\.ya?ml$/;
|
|
55
|
+
function listFiles(directory, pattern, recursive) {
|
|
56
|
+
if (!existsSync(directory)) return [];
|
|
57
|
+
return readdirSync(directory, {
|
|
58
|
+
recursive,
|
|
59
|
+
withFileTypes: true
|
|
60
|
+
}).filter((entry) => (entry.isFile() || entry.isSymbolicLink()) && pattern.test(entry.name)).map((entry) => join(entry.parentPath, entry.name));
|
|
61
|
+
}
|
|
62
|
+
/** GitHub only runs top-level workflow files; composite actions nest freely. */
|
|
63
|
+
function listActionFilesIn(rootDirectory) {
|
|
64
|
+
return [
|
|
65
|
+
...listFiles(join(rootDirectory, WORKFLOWS_DIRECTORY), YAML_PATTERN, false),
|
|
66
|
+
...listFiles(join(rootDirectory, ACTIONS_DIRECTORY), ACTION_FILE_PATTERN, true),
|
|
67
|
+
...listFiles(rootDirectory, ACTION_FILE_PATTERN, false)
|
|
68
|
+
].map((path) => relative(rootDirectory, path)).sort();
|
|
69
|
+
}
|
|
70
|
+
const systemEnvironment = {
|
|
71
|
+
listActionFiles: () => listActionFilesIn("."),
|
|
72
|
+
readTextFile: (path) => readFileSync(path, "utf-8")
|
|
73
|
+
};
|
|
74
|
+
function checkFiles(files, environment) {
|
|
75
|
+
const violations = files.flatMap((file) => findPinningViolations(file, environment.readTextFile(file)));
|
|
76
|
+
for (const violation of violations) console.error(`np-check-action-pinning: ${formatViolation(violation)}`);
|
|
77
|
+
if (violations.length === 0) console.log(`np-check-action-pinning: ${files.length} files, all pinned`);
|
|
78
|
+
return violations.length > 0 ? 1 : 0;
|
|
79
|
+
}
|
|
80
|
+
/** Checks workflows and composite actions in the working directory; returns the exit code. */
|
|
81
|
+
function runActionPinningCheck(environment = systemEnvironment) {
|
|
82
|
+
try {
|
|
83
|
+
const files = environment.listActionFiles();
|
|
84
|
+
if (files.length === 0) {
|
|
85
|
+
console.error(`np-check-action-pinning: no files found under ${WORKFLOWS_DIRECTORY}, run it from the repository root`);
|
|
86
|
+
return 1;
|
|
87
|
+
}
|
|
88
|
+
return checkFiles(files, environment);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
91
|
+
console.error(`np-check-action-pinning: ${reason}`);
|
|
92
|
+
return 1;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// src/check-action-pinning.ts
|
|
96
|
+
process.exitCode = runActionPinningCheck();
|
|
97
|
+
export {};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { appendFileSync } from "node:fs";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { i as createNetlifyClient, n as escapeWorkflowCommand, t as describeError } from "./workflow-command-BkYMh3G8.js";
|
|
5
|
+
// src/should-deploy/decide.ts
|
|
6
|
+
const READY_STATE = "ready";
|
|
7
|
+
const PRODUCTION_CONTEXT = "production";
|
|
8
|
+
function findLastDeployedSha(deploys) {
|
|
9
|
+
return deploys.find((deploy) => deploy.state === READY_STATE && deploy.context === PRODUCTION_CONTEXT && deploy.commitRef !== null)?.commitRef ?? null;
|
|
10
|
+
}
|
|
11
|
+
function decideDeploy(currentSha, lastDeployedSha) {
|
|
12
|
+
if (currentSha === null) return {
|
|
13
|
+
deploy: true,
|
|
14
|
+
reason: "The current commit is unknown, so deploying."
|
|
15
|
+
};
|
|
16
|
+
if (lastDeployedSha === null) return {
|
|
17
|
+
deploy: true,
|
|
18
|
+
reason: "No successful production deploy found, so deploying."
|
|
19
|
+
};
|
|
20
|
+
if (lastDeployedSha.toLowerCase() === currentSha.toLowerCase()) return {
|
|
21
|
+
deploy: false,
|
|
22
|
+
reason: `${currentSha} is already live, skipping the deploy.`
|
|
23
|
+
};
|
|
24
|
+
return {
|
|
25
|
+
deploy: true,
|
|
26
|
+
reason: `Last deployed ${lastDeployedSha}, main is ${currentSha}, so deploying.`
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
// src/should-deploy/run.ts
|
|
30
|
+
const systemEnvironment = {
|
|
31
|
+
variables: process.env,
|
|
32
|
+
createClient: (siteId, token) => createNetlifyClient({
|
|
33
|
+
siteId,
|
|
34
|
+
token
|
|
35
|
+
}),
|
|
36
|
+
appendOutput: (path, text) => appendFileSync(path, text)
|
|
37
|
+
};
|
|
38
|
+
function log(message) {
|
|
39
|
+
console.log(`np-should-deploy: ${escapeWorkflowCommand(message)}`);
|
|
40
|
+
}
|
|
41
|
+
async function lookUpLastDeployedSha(environment) {
|
|
42
|
+
const siteId = environment.variables["NETLIFY_SITE_ID"];
|
|
43
|
+
const token = environment.variables["NETLIFY_AUTH_TOKEN"];
|
|
44
|
+
if (!siteId || !token) {
|
|
45
|
+
log("NETLIFY_SITE_ID or NETLIFY_AUTH_TOKEN is not set, cannot find the live commit.");
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
return findLastDeployedSha(await environment.createClient(siteId, token).listProductionDeploys());
|
|
50
|
+
} catch (error) {
|
|
51
|
+
log(`could not read the last deploy (${describeError(error)}).`);
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function writeDecision(environment, deploy) {
|
|
56
|
+
const outputPath = environment.variables["GITHUB_OUTPUT"];
|
|
57
|
+
if (!outputPath) {
|
|
58
|
+
log("GITHUB_OUTPUT is not set, so the decision was not written.");
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
environment.appendOutput(outputPath, `skip=${!deploy}\n`);
|
|
62
|
+
}
|
|
63
|
+
/** Decides whether to deploy, writes `skip=<bool>` to GITHUB_OUTPUT, and returns the exit code. */
|
|
64
|
+
async function runShouldDeploy(argv, environment = systemEnvironment) {
|
|
65
|
+
try {
|
|
66
|
+
parseArgs({
|
|
67
|
+
args: argv,
|
|
68
|
+
options: {}
|
|
69
|
+
});
|
|
70
|
+
const currentSha = environment.variables["CURRENT_SHA"] || null;
|
|
71
|
+
const { deploy, reason } = decideDeploy(currentSha, currentSha === null ? null : await lookUpLastDeployedSha(environment));
|
|
72
|
+
log(reason);
|
|
73
|
+
writeDecision(environment, deploy);
|
|
74
|
+
return 0;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
console.error(`np-should-deploy: ${describeError(error)}`);
|
|
77
|
+
return 1;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
// src/should-deploy.ts
|
|
81
|
+
process.exitCode = await runShouldDeploy(process.argv.slice(2));
|
|
82
|
+
export {};
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { i as createNetlifyClient, n as escapeWorkflowCommand, r as NetlifyFatalError, t as describeError } from "./workflow-command-BkYMh3G8.js";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
// src/verify-deploy/evaluate.ts
|
|
5
|
+
const SUCCESS_STATES = /* @__PURE__ */ new Set(["ready"]);
|
|
6
|
+
const FAILURE_STATES = /* @__PURE__ */ new Set([
|
|
7
|
+
"error",
|
|
8
|
+
"cancelled",
|
|
9
|
+
"canceled",
|
|
10
|
+
"rejected",
|
|
11
|
+
"skipped"
|
|
12
|
+
]);
|
|
13
|
+
const PRODUCTION_CONTEXT = "production";
|
|
14
|
+
const CLOCK_SKEW_MS = 12e4;
|
|
15
|
+
const DEPLOY_ID_PATTERN = /^[0-9a-f]{24}$/;
|
|
16
|
+
function classifyDeployState(state) {
|
|
17
|
+
if (SUCCESS_STATES.has(state)) return "success";
|
|
18
|
+
if (FAILURE_STATES.has(state)) return "failure";
|
|
19
|
+
return "pending";
|
|
20
|
+
}
|
|
21
|
+
/** The newest production deploy carrying the trigger title, created after the trigger fired. */
|
|
22
|
+
function findTriggeredDeploy(deploys, target) {
|
|
23
|
+
const earliest = Date.parse(target.triggeredAt) - CLOCK_SKEW_MS;
|
|
24
|
+
return deploys.find((deploy) => deploy.context === PRODUCTION_CONTEXT && deploy.title === target.title && deploy.createdAt !== null && Date.parse(deploy.createdAt) >= earliest) ?? null;
|
|
25
|
+
}
|
|
26
|
+
/** GET /deploys/{id} returns any deploy the token can read, so confirm it is this site's production deploy. */
|
|
27
|
+
function describeOwnershipProblem(deploy, siteId) {
|
|
28
|
+
if (deploy.siteId !== siteId) return `Deploy ${deploy.id} does not belong to the site named by NETLIFY_SITE_ID.`;
|
|
29
|
+
if (deploy.context !== PRODUCTION_CONTEXT) return `Deploy ${deploy.id} is a "${deploy.context ?? "unknown"}" deploy, not a production deploy.`;
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
function describeFailure(deploy) {
|
|
33
|
+
const detail = deploy.errorMessage ? `: ${deploy.errorMessage}` : "";
|
|
34
|
+
return `Netlify production deploy ${deploy.id} ended in state "${deploy.state}"${detail}. See ${deploy.adminUrl ?? "the Netlify deploys page"}.`;
|
|
35
|
+
}
|
|
36
|
+
function describeCommitProblem(deploy, expectedSha) {
|
|
37
|
+
if (deploy.commitRef === null) return `Netlify production deploy ${deploy.id} is ready but reported no commit, so it cannot be shown to match the expected commit ${expectedSha}.`;
|
|
38
|
+
if (deploy.commitRef.toLowerCase() === expectedSha.toLowerCase()) return null;
|
|
39
|
+
return `Netlify deployed ${deploy.commitRef}, but the expected commit is ${expectedSha}, so the deployed commit was not the one checked (most likely main moved after the check). Start a new run, or roll back in Netlify if it is unsafe.`;
|
|
40
|
+
}
|
|
41
|
+
function evaluateDeploy(deploy, expectedSha) {
|
|
42
|
+
const outcome = classifyDeployState(deploy.state);
|
|
43
|
+
if (outcome === "pending") return { status: "pending" };
|
|
44
|
+
if (outcome === "failure") return {
|
|
45
|
+
status: "failed",
|
|
46
|
+
message: describeFailure(deploy)
|
|
47
|
+
};
|
|
48
|
+
const commitProblem = expectedSha === null ? null : describeCommitProblem(deploy, expectedSha);
|
|
49
|
+
return commitProblem === null ? { status: "live" } : {
|
|
50
|
+
status: "failed",
|
|
51
|
+
message: commitProblem
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
// src/verify-deploy/config.ts
|
|
55
|
+
const DEFAULT_TIMEOUT_SECONDS = 1200;
|
|
56
|
+
const MILLISECONDS_PER_SECOND$1 = 1e3;
|
|
57
|
+
const MAX_SECONDS = 21600;
|
|
58
|
+
const MISSING_VARIABLE_HINTS = {
|
|
59
|
+
NETLIFY_AUTH_TOKEN: "a Netlify personal access token, so the workflow can confirm the production build succeeded",
|
|
60
|
+
NETLIFY_SITE_ID: "the Netlify site id (Site configuration > Site details), so the workflow can find the deploy",
|
|
61
|
+
NETLIFY_TRIGGER_TITLE: "the title the trigger step sent to the build hook, or set NETLIFY_VERIFY_DEPLOY_ID to verify a known deploy",
|
|
62
|
+
NETLIFY_TRIGGERED_AT: "when the trigger step called the build hook (an ISO 8601 date)"
|
|
63
|
+
};
|
|
64
|
+
const TRIGGER_VARIABLES = ["NETLIFY_TRIGGER_TITLE", "NETLIFY_TRIGGERED_AT"];
|
|
65
|
+
function parseSeconds(flag, value, fallback) {
|
|
66
|
+
if (value === void 0) return fallback;
|
|
67
|
+
const seconds = Number(value);
|
|
68
|
+
if (!Number.isInteger(seconds) || seconds < 1 || seconds > MAX_SECONDS) throw new Error(`--${flag} must be a whole number of seconds from 1 to ${MAX_SECONDS}`);
|
|
69
|
+
return seconds;
|
|
70
|
+
}
|
|
71
|
+
function requiredVariableNames(verifyOnly) {
|
|
72
|
+
return Object.keys(MISSING_VARIABLE_HINTS).filter((name) => !verifyOnly || !TRIGGER_VARIABLES.includes(name));
|
|
73
|
+
}
|
|
74
|
+
function readDeployId(variables) {
|
|
75
|
+
const deployId = (variables["NETLIFY_VERIFY_DEPLOY_ID"] ?? "").trim();
|
|
76
|
+
if (deployId === "") return null;
|
|
77
|
+
if (!DEPLOY_ID_PATTERN.test(deployId)) throw new Error("NETLIFY_VERIFY_DEPLOY_ID must be a 24 character lowercase hexadecimal Netlify deploy id");
|
|
78
|
+
return deployId;
|
|
79
|
+
}
|
|
80
|
+
function assertNoneMissing(variables, names) {
|
|
81
|
+
const missing = names.filter((name) => !variables[name]);
|
|
82
|
+
if (missing.length === 0) return;
|
|
83
|
+
const hints = missing.map((name) => `${name} (${MISSING_VARIABLE_HINTS[name]})`);
|
|
84
|
+
throw new Error(`missing ${hints.join("; ")}`);
|
|
85
|
+
}
|
|
86
|
+
function readTarget(variables, deployId) {
|
|
87
|
+
if (deployId !== null) return {
|
|
88
|
+
kind: "deploy-id",
|
|
89
|
+
deployId
|
|
90
|
+
};
|
|
91
|
+
const title = variables["NETLIFY_TRIGGER_TITLE"] ?? "";
|
|
92
|
+
const triggeredAt = variables["NETLIFY_TRIGGERED_AT"] ?? "";
|
|
93
|
+
if (Number.isNaN(Date.parse(triggeredAt))) throw new Error(`NETLIFY_TRIGGERED_AT is not a valid date: "${triggeredAt}"`);
|
|
94
|
+
return {
|
|
95
|
+
kind: "trigger",
|
|
96
|
+
title,
|
|
97
|
+
triggeredAt
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function readConfig(argv, variables) {
|
|
101
|
+
const { values } = parseArgs({
|
|
102
|
+
args: argv,
|
|
103
|
+
options: {
|
|
104
|
+
"timeout-seconds": { type: "string" },
|
|
105
|
+
"interval-seconds": { type: "string" }
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
const timeoutSeconds = parseSeconds("timeout-seconds", values["timeout-seconds"], DEFAULT_TIMEOUT_SECONDS);
|
|
109
|
+
const intervalSeconds = parseSeconds("interval-seconds", values["interval-seconds"], 15);
|
|
110
|
+
const deployId = readDeployId(variables);
|
|
111
|
+
assertNoneMissing(variables, requiredVariableNames(deployId !== null));
|
|
112
|
+
return {
|
|
113
|
+
token: variables["NETLIFY_AUTH_TOKEN"] ?? "",
|
|
114
|
+
request: {
|
|
115
|
+
siteId: variables["NETLIFY_SITE_ID"] ?? "",
|
|
116
|
+
target: readTarget(variables, deployId),
|
|
117
|
+
expectedSha: variables["EXPECTED_COMMIT_SHA"] || null,
|
|
118
|
+
timeoutMs: timeoutSeconds * MILLISECONDS_PER_SECOND$1,
|
|
119
|
+
intervalMs: intervalSeconds * MILLISECONDS_PER_SECOND$1
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
// src/verify-deploy/poll.ts
|
|
124
|
+
const MILLISECONDS_PER_SECOND = 1e3;
|
|
125
|
+
function describeTarget(target) {
|
|
126
|
+
return target.kind === "deploy-id" ? target.deployId : `"${target.title}"`;
|
|
127
|
+
}
|
|
128
|
+
async function fetchTargetDeploy(request, client) {
|
|
129
|
+
const { target } = request;
|
|
130
|
+
if (target.kind === "deploy-id") return client.getDeploy(target.deployId);
|
|
131
|
+
return findTriggeredDeploy(await client.listProductionDeploys(), target);
|
|
132
|
+
}
|
|
133
|
+
function judgeDeploy(request, deploy, log) {
|
|
134
|
+
log(`Deploy ${deploy.id}: ${deploy.state}`);
|
|
135
|
+
const ownershipProblem = request.target.kind === "deploy-id" ? describeOwnershipProblem(deploy, request.siteId) : null;
|
|
136
|
+
if (ownershipProblem !== null) return { done: {
|
|
137
|
+
ok: false,
|
|
138
|
+
message: ownershipProblem
|
|
139
|
+
} };
|
|
140
|
+
const evaluation = evaluateDeploy(deploy, request.expectedSha);
|
|
141
|
+
if (evaluation.status === "failed") return { done: {
|
|
142
|
+
ok: false,
|
|
143
|
+
message: evaluation.message
|
|
144
|
+
} };
|
|
145
|
+
if (evaluation.status === "live") return { done: {
|
|
146
|
+
ok: true,
|
|
147
|
+
deploy
|
|
148
|
+
} };
|
|
149
|
+
return { observation: `state "${deploy.state}"` };
|
|
150
|
+
}
|
|
151
|
+
async function pollOnce(request, environment) {
|
|
152
|
+
try {
|
|
153
|
+
const deploy = await fetchTargetDeploy(request, environment.client);
|
|
154
|
+
if (deploy === null) {
|
|
155
|
+
const observation = `no production deploy titled ${describeTarget(request.target)} listed yet`;
|
|
156
|
+
environment.log(`No Netlify deploy found: ${observation}`);
|
|
157
|
+
return { observation };
|
|
158
|
+
}
|
|
159
|
+
return judgeDeploy(request, deploy, environment.log);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
const reason = describeError(error);
|
|
162
|
+
if (error instanceof NetlifyFatalError) return { done: {
|
|
163
|
+
ok: false,
|
|
164
|
+
message: reason
|
|
165
|
+
} };
|
|
166
|
+
environment.log(`Netlify API error (will retry): ${reason}`);
|
|
167
|
+
return { observation: reason };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function timeoutResult(request, lastObservation) {
|
|
171
|
+
return {
|
|
172
|
+
ok: false,
|
|
173
|
+
message: `Timed out after ${Math.round(request.timeoutMs / MILLISECONDS_PER_SECOND)} seconds waiting for the Netlify deploy ${describeTarget(request.target)}; last observed ${lastObservation}.`
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
async function verifyDeploy(request, environment) {
|
|
177
|
+
const deadline = environment.now() + request.timeoutMs;
|
|
178
|
+
while (true) {
|
|
179
|
+
const step = await pollOnce(request, environment);
|
|
180
|
+
if (step.done) return step.done;
|
|
181
|
+
if (environment.now() >= deadline) return timeoutResult(request, step.observation);
|
|
182
|
+
await environment.sleep(Math.min(request.intervalMs, deadline - environment.now()));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
// src/verify-deploy/run.ts
|
|
186
|
+
const systemEnvironment = {
|
|
187
|
+
variables: process.env,
|
|
188
|
+
createClient: (siteId, token) => createNetlifyClient({
|
|
189
|
+
siteId,
|
|
190
|
+
token
|
|
191
|
+
}),
|
|
192
|
+
sleep: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
|
|
193
|
+
now: () => Date.now()
|
|
194
|
+
};
|
|
195
|
+
function logLine(message) {
|
|
196
|
+
console.log(`np-verify-netlify-deploy: ${escapeWorkflowCommand(message)}`);
|
|
197
|
+
}
|
|
198
|
+
function reportFailure(message) {
|
|
199
|
+
console.error(`::error::np-verify-netlify-deploy: ${escapeWorkflowCommand(message)}`);
|
|
200
|
+
}
|
|
201
|
+
/** Waits for the Netlify deploy to go live on the expected commit; returns the exit code. */
|
|
202
|
+
async function runVerifyNetlifyDeploy(argv, environment = systemEnvironment) {
|
|
203
|
+
try {
|
|
204
|
+
const { token, request } = readConfig(argv, environment.variables);
|
|
205
|
+
const result = await verifyDeploy(request, {
|
|
206
|
+
client: environment.createClient(request.siteId, token),
|
|
207
|
+
sleep: environment.sleep,
|
|
208
|
+
now: environment.now,
|
|
209
|
+
log: logLine
|
|
210
|
+
});
|
|
211
|
+
if (!result.ok) {
|
|
212
|
+
reportFailure(result.message);
|
|
213
|
+
return 1;
|
|
214
|
+
}
|
|
215
|
+
logLine(`Netlify production deploy ${result.deploy.id} is live.`);
|
|
216
|
+
return 0;
|
|
217
|
+
} catch (error) {
|
|
218
|
+
reportFailure(describeError(error));
|
|
219
|
+
return 1;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// src/verify-netlify-deploy.ts
|
|
223
|
+
process.exitCode = await runVerifyNetlifyDeploy(process.argv.slice(2));
|
|
224
|
+
export {};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// src/netlify/client.ts
|
|
2
|
+
const NETLIFY_API_BASE_URL = "https://api.netlify.com/api/v1";
|
|
3
|
+
const REQUEST_TIMEOUT_MS = 3e4;
|
|
4
|
+
const DEPLOYS_PAGE_SIZE = 20;
|
|
5
|
+
const AUTH_FAILURE_STATUSES = /* @__PURE__ */ new Set([401, 403]);
|
|
6
|
+
const NOT_FOUND_STATUS = 404;
|
|
7
|
+
const REQUEST_TIMEOUT_STATUS = 408;
|
|
8
|
+
const TOO_MANY_REQUESTS_STATUS = 429;
|
|
9
|
+
const CLIENT_ERROR_MIN_STATUS = 400;
|
|
10
|
+
const SERVER_ERROR_MIN_STATUS = 500;
|
|
11
|
+
/** An error retrying cannot fix: bad token, wrong site id, unexpected payload. */
|
|
12
|
+
var NetlifyFatalError = class extends Error {};
|
|
13
|
+
function textOrNull(value) {
|
|
14
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
15
|
+
}
|
|
16
|
+
function parseDeploy(value) {
|
|
17
|
+
if (typeof value !== "object" || value === null) throw new NetlifyFatalError("Netlify returned an unexpected payload (expected a deploy object).");
|
|
18
|
+
const record = value;
|
|
19
|
+
return {
|
|
20
|
+
id: textOrNull(record["id"]) ?? "unknown",
|
|
21
|
+
state: textOrNull(record["state"]) ?? "unknown",
|
|
22
|
+
title: textOrNull(record["title"]),
|
|
23
|
+
context: textOrNull(record["context"]),
|
|
24
|
+
commitRef: textOrNull(record["commit_ref"]),
|
|
25
|
+
createdAt: textOrNull(record["created_at"]),
|
|
26
|
+
siteId: textOrNull(record["site_id"]),
|
|
27
|
+
errorMessage: textOrNull(record["error_message"]),
|
|
28
|
+
adminUrl: textOrNull(record["admin_url"])
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function parseDeployList(value) {
|
|
32
|
+
if (!Array.isArray(value)) throw new NetlifyFatalError("Netlify returned an unexpected payload (expected a list of deploys).");
|
|
33
|
+
return value.map(parseDeploy);
|
|
34
|
+
}
|
|
35
|
+
function failureFor(status) {
|
|
36
|
+
const message = `Netlify API responded with HTTP ${status}`;
|
|
37
|
+
return status >= SERVER_ERROR_MIN_STATUS || status < CLIENT_ERROR_MIN_STATUS || status === REQUEST_TIMEOUT_STATUS || status === TOO_MANY_REQUESTS_STATUS ? new Error(message) : new NetlifyFatalError(message);
|
|
38
|
+
}
|
|
39
|
+
async function readJson(response) {
|
|
40
|
+
try {
|
|
41
|
+
return await response.json();
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
44
|
+
throw new NetlifyFatalError(`Netlify returned a body that is not JSON (HTTP ${response.status}).`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function createNetlifyClient(options) {
|
|
48
|
+
const { siteId, token, fetchImpl = fetch } = options;
|
|
49
|
+
async function getJson(path) {
|
|
50
|
+
const response = await fetchImpl(`${NETLIFY_API_BASE_URL}${path}`, {
|
|
51
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
52
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
53
|
+
});
|
|
54
|
+
if (AUTH_FAILURE_STATUSES.has(response.status)) throw new NetlifyFatalError(`Netlify API rejected NETLIFY_AUTH_TOKEN (HTTP ${response.status}); check the token is valid and can read this site.`);
|
|
55
|
+
if (response.status === NOT_FOUND_STATUS) throw new NetlifyFatalError(`Netlify API returned 404 for ${path}; check NETLIFY_SITE_ID names this site and NETLIFY_VERIFY_DEPLOY_ID, if set, is one of its deploys.`);
|
|
56
|
+
if (!response.ok) throw failureFor(response.status);
|
|
57
|
+
return readJson(response);
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
async listProductionDeploys() {
|
|
61
|
+
const query = `production=true&per_page=${DEPLOYS_PAGE_SIZE}`;
|
|
62
|
+
return parseDeployList(await getJson(`/sites/${encodeURIComponent(siteId)}/deploys?${query}`));
|
|
63
|
+
},
|
|
64
|
+
async getDeploy(deployId) {
|
|
65
|
+
return parseDeploy(await getJson(`/deploys/${encodeURIComponent(deployId)}`));
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
// src/workflow-command.ts
|
|
70
|
+
function describeError(error) {
|
|
71
|
+
return error instanceof Error ? error.message : String(error);
|
|
72
|
+
}
|
|
73
|
+
function escapeWorkflowCommand(text) {
|
|
74
|
+
return text.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
|
|
75
|
+
}
|
|
76
|
+
export { createNetlifyClient as i, escapeWorkflowCommand as n, NetlifyFatalError as r, describeError as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neon-pixels/scripts",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "CI and deploy scripts for Neon Pixels projects: dependency audit gate, GitHub Actions pinning check, and Netlify production deploy checks.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/neonpixels-studio/packages.git",
|
|
10
|
+
"directory": "packages/scripts"
|
|
11
|
+
},
|
|
12
|
+
"bin": {
|
|
13
|
+
"np-audit-gate": "./dist/audit-gate.js",
|
|
14
|
+
"np-check-action-pinning": "./dist/check-action-pinning.js",
|
|
15
|
+
"np-should-deploy": "./dist/should-deploy.js",
|
|
16
|
+
"np-verify-netlify-deploy": "./dist/verify-netlify-deploy.js"
|
|
17
|
+
},
|
|
18
|
+
"exports": {
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": "^22.17.0 || ^24.0.0 || >=26.0.0"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "tsdown",
|
|
32
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
33
|
+
}
|
|
6
34
|
}
|