@agenticcli/shipguard 0.8.1 → 0.10.0-rc.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 +23 -5
- package/dist/checksum-manifest.json +5 -5
- package/dist/{chunk-BGWAAJ5S.js → chunk-6XMYOF3N.js} +3 -38
- package/dist/chunk-E4Z2MZ5J.js +904 -0
- package/dist/chunk-NC5RELTG.js +40 -0
- package/dist/cli-facts.json +8 -5
- package/dist/cli.js +618 -489
- package/dist/{config-generator-4MK6PGY5.js → config-generator-S5KFHKGQ.js} +2 -1
- package/dist/{pro-scanner-ZKL6L5L6.js → pro-scanner-TPNDJ6L6.js} +2 -1
- package/docs/llms.txt +1 -1
- package/package.json +6 -8
- package/dist/chunk-MVYY4QWT.js +0 -176
|
@@ -0,0 +1,904 @@
|
|
|
1
|
+
import {
|
|
2
|
+
logger
|
|
3
|
+
} from "./chunk-NC5RELTG.js";
|
|
4
|
+
import {
|
|
5
|
+
decodeUtf8Strict,
|
|
6
|
+
detectBinary,
|
|
7
|
+
normalizeNewlines,
|
|
8
|
+
stripBom
|
|
9
|
+
} from "./chunk-KGIK7XNK.js";
|
|
10
|
+
|
|
11
|
+
// src/utils/fs.ts
|
|
12
|
+
import fg from "fast-glob";
|
|
13
|
+
import { open, readFile, readdir, stat } from "fs/promises";
|
|
14
|
+
import { join as join3 } from "path";
|
|
15
|
+
|
|
16
|
+
// src/utils/classify.ts
|
|
17
|
+
var CONTROL_WINDOW_BYTES = 32 * 1024;
|
|
18
|
+
var NUL_SHARE_MAX = 0.01;
|
|
19
|
+
var CONTROL_SHARE_MAX = 0.05;
|
|
20
|
+
var PRINTABLE_SHARE_BINARY_BELOW = 0.7;
|
|
21
|
+
var UTF16_NUL_SHARE_MAX = 0.01;
|
|
22
|
+
var UTF16_CONTROL_SHARE_MAX = 0.05;
|
|
23
|
+
var UTF16_BLOCK_SHARE_MIN = 0.8;
|
|
24
|
+
var UTF16_PARITY_DOMINANCE = 4;
|
|
25
|
+
var HEAD_BYTES = 4096;
|
|
26
|
+
var startsWith = (b, sig, at = 0) => b.length >= at + sig.length && sig.every((v, i) => b[at + i] === v);
|
|
27
|
+
var ascii = (s) => Array.from(s, (c) => c.charCodeAt(0));
|
|
28
|
+
function matchMagic(b) {
|
|
29
|
+
const m = (name, length) => ({ name, length });
|
|
30
|
+
if (startsWith(b, [137, 80, 78, 71])) return m("png", 4);
|
|
31
|
+
if (startsWith(b, [255, 216, 255])) return m("jpeg", 3);
|
|
32
|
+
if (startsWith(b, ascii("GIF8"))) return m("gif", 4);
|
|
33
|
+
if (startsWith(b, ascii("RIFF")) && startsWith(b, ascii("WEBP"), 8)) return m("webp", 12);
|
|
34
|
+
if (startsWith(b, [0, 0, 1, 0])) return m("ico", 4);
|
|
35
|
+
if (startsWith(b, ascii("%PDF"))) return m("pdf", 4);
|
|
36
|
+
if (startsWith(b, [80, 75, 3, 4])) return m("zip", 4);
|
|
37
|
+
if (startsWith(b, [31, 139])) return m("gzip", 2);
|
|
38
|
+
if (startsWith(b, ascii("BZh"))) return m("bzip2", 3);
|
|
39
|
+
if (startsWith(b, [253, 55, 122, 88, 90, 0])) return m("xz", 6);
|
|
40
|
+
if (startsWith(b, [55, 122, 188, 175, 39, 28])) return m("7z", 6);
|
|
41
|
+
if (startsWith(b, ascii("ustar"), 257)) return m("tar", 262);
|
|
42
|
+
if (startsWith(b, [127, 69, 76, 70])) return m("elf", 4);
|
|
43
|
+
if (startsWith(b, [254, 237, 250, 206]) || startsWith(b, [254, 237, 250, 207]) || startsWith(b, [206, 250, 237, 254]) || startsWith(b, [207, 250, 237, 254])) return m("macho", 4);
|
|
44
|
+
if (startsWith(b, [77, 90])) return m("pe", 2);
|
|
45
|
+
if (startsWith(b, [0, 97, 115, 109])) return m("wasm", 4);
|
|
46
|
+
if (startsWith(b, ascii("SQLite format 3"))) return m("sqlite", 16);
|
|
47
|
+
if (startsWith(b, ascii("wOFF"))) return m("woff", 4);
|
|
48
|
+
if (startsWith(b, ascii("wOF2"))) return m("woff2", 4);
|
|
49
|
+
if (startsWith(b, [0, 1, 0, 0])) return m("ttf", 4);
|
|
50
|
+
if (startsWith(b, ascii("OTTO"))) return m("otf", 4);
|
|
51
|
+
if (startsWith(b, ascii("ftyp"), 4)) return m("mp4", 8);
|
|
52
|
+
if (startsWith(b, [202, 254, 186, 190])) return m("class", 4);
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
var STRINGS_READABLE = /* @__PURE__ */ new Set(["sqlite", "tar"]);
|
|
56
|
+
var isTextWhitespace = (b) => b === 9 || b === 10 || b === 12 || b === 13;
|
|
57
|
+
function utf8SeqLen(b, i) {
|
|
58
|
+
const c = b[i];
|
|
59
|
+
const cont = (k, lo = 128, hi = 191) => i + k < b.length && b[i + k] >= lo && b[i + k] <= hi;
|
|
60
|
+
if (c >= 194 && c <= 223) return cont(1) ? 2 : 0;
|
|
61
|
+
if (c === 224) return cont(1, 160, 191) && cont(2) ? 3 : 0;
|
|
62
|
+
if (c >= 225 && c <= 236 || c === 238 || c === 239) return cont(1) && cont(2) ? 3 : 0;
|
|
63
|
+
if (c === 237) return cont(1, 128, 159) && cont(2) ? 3 : 0;
|
|
64
|
+
if (c === 240) return cont(1, 144, 191) && cont(2) && cont(3) ? 4 : 0;
|
|
65
|
+
if (c >= 241 && c <= 243) return cont(1) && cont(2) && cont(3) ? 4 : 0;
|
|
66
|
+
if (c === 244) return cont(1, 128, 143) && cont(2) && cont(3) ? 4 : 0;
|
|
67
|
+
return 0;
|
|
68
|
+
}
|
|
69
|
+
function printableShare(b) {
|
|
70
|
+
if (b.length === 0) return 1;
|
|
71
|
+
let printable = 0;
|
|
72
|
+
for (let i = 0; i < b.length; ) {
|
|
73
|
+
const c = b[i];
|
|
74
|
+
if (c >= 32 && c <= 126 || isTextWhitespace(c)) {
|
|
75
|
+
printable++;
|
|
76
|
+
i++;
|
|
77
|
+
} else if (c >= 194) {
|
|
78
|
+
const n = utf8SeqLen(b, i);
|
|
79
|
+
if (n > 0) {
|
|
80
|
+
printable += n;
|
|
81
|
+
i += n;
|
|
82
|
+
} else i++;
|
|
83
|
+
} else i++;
|
|
84
|
+
}
|
|
85
|
+
return printable / b.length;
|
|
86
|
+
}
|
|
87
|
+
function isRealBinary(b) {
|
|
88
|
+
const magic = matchMagic(b);
|
|
89
|
+
if (!magic) return null;
|
|
90
|
+
return printableShare(b) < PRINTABLE_SHARE_BINARY_BELOW ? magic : null;
|
|
91
|
+
}
|
|
92
|
+
function validUtf8WithCutTail(b) {
|
|
93
|
+
for (let cut = 0; cut <= 3 && cut <= b.length; cut++) {
|
|
94
|
+
if (decodeUtf8Strict(b.subarray(0, b.length - cut)).ok) return true;
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
function headLooksLikeRealBinary(head) {
|
|
99
|
+
const h = head.subarray(0, HEAD_BYTES);
|
|
100
|
+
const magic = matchMagic(h);
|
|
101
|
+
if (!magic) return false;
|
|
102
|
+
return !validUtf8WithCutTail(h.subarray(Math.min(magic.length, h.length)));
|
|
103
|
+
}
|
|
104
|
+
var finish = (s) => normalizeNewlines(stripBom(s));
|
|
105
|
+
function fromCharCodes(u16) {
|
|
106
|
+
const parts = [];
|
|
107
|
+
const CHUNK = 8192;
|
|
108
|
+
for (let i = 0; i < u16.length; i += CHUNK) {
|
|
109
|
+
parts.push(String.fromCharCode.apply(null, Array.from(u16.subarray(i, i + CHUNK))));
|
|
110
|
+
}
|
|
111
|
+
return parts.join("");
|
|
112
|
+
}
|
|
113
|
+
function decodeUtf16(b, bigEndian) {
|
|
114
|
+
if (b.length % 2 !== 0) return null;
|
|
115
|
+
const n = b.length / 2;
|
|
116
|
+
const u = new Uint16Array(n);
|
|
117
|
+
for (let i = 0; i < n; i++) {
|
|
118
|
+
u[i] = bigEndian ? b[2 * i] << 8 | b[2 * i + 1] : b[2 * i + 1] << 8 | b[2 * i];
|
|
119
|
+
}
|
|
120
|
+
for (let i = 0; i < n; i++) {
|
|
121
|
+
const c = u[i];
|
|
122
|
+
if (c >= 55296 && c <= 56319) {
|
|
123
|
+
if (i + 1 >= n || u[i + 1] < 56320 || u[i + 1] > 57343) return null;
|
|
124
|
+
i++;
|
|
125
|
+
} else if (c >= 56320 && c <= 57343) return null;
|
|
126
|
+
}
|
|
127
|
+
return u;
|
|
128
|
+
}
|
|
129
|
+
var BLOCKS = [
|
|
130
|
+
[9, 13],
|
|
131
|
+
[32, 126],
|
|
132
|
+
[160, 591],
|
|
133
|
+
[880, 8191],
|
|
134
|
+
[8192, 8303],
|
|
135
|
+
[12288, 40959],
|
|
136
|
+
[44032, 55215],
|
|
137
|
+
[65280, 65519]
|
|
138
|
+
];
|
|
139
|
+
function plausibleUtf16(u) {
|
|
140
|
+
if (u.length === 0) return false;
|
|
141
|
+
let nul = 0;
|
|
142
|
+
let control = 0;
|
|
143
|
+
let inBlocks = 0;
|
|
144
|
+
for (let i = 0; i < u.length; i++) {
|
|
145
|
+
const c = u[i];
|
|
146
|
+
if (c === 0) nul++;
|
|
147
|
+
else if (c < 32 && !(c >= 9 && c <= 13)) control++;
|
|
148
|
+
else if (c >= 127 && c < 160) control++;
|
|
149
|
+
for (const [lo, hi] of BLOCKS) {
|
|
150
|
+
if (c >= lo && c <= hi) {
|
|
151
|
+
inBlocks++;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return nul / u.length <= UTF16_NUL_SHARE_MAX && control / u.length <= UTF16_CONTROL_SHARE_MAX && inBlocks / u.length >= UTF16_BLOCK_SHARE_MIN;
|
|
157
|
+
}
|
|
158
|
+
function nulParity(b) {
|
|
159
|
+
let even = 0;
|
|
160
|
+
let odd = 0;
|
|
161
|
+
for (let i = 0; i < b.length; i++) {
|
|
162
|
+
if (b[i] === 0) i & 1 ? odd++ : even++;
|
|
163
|
+
}
|
|
164
|
+
if (odd > 0 && odd >= UTF16_PARITY_DOMINANCE * even) return "le";
|
|
165
|
+
if (even > 0 && even >= UTF16_PARITY_DOMINANCE * odd) return "be";
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
function nulSubstitutedReading(b) {
|
|
169
|
+
let nul = 0;
|
|
170
|
+
for (let i = 0; i < b.length; i++) if (b[i] === 0) nul++;
|
|
171
|
+
if (nul / b.length > NUL_SHARE_MAX) return null;
|
|
172
|
+
const s = new Uint8Array(b);
|
|
173
|
+
for (let i = 0; i < s.length; i++) if (s[i] === 0) s[i] = 32;
|
|
174
|
+
const win = Math.min(s.length, CONTROL_WINDOW_BYTES);
|
|
175
|
+
let control = 0;
|
|
176
|
+
for (let i = 0; i < win; i++) if (s[i] < 32 && !isTextWhitespace(s[i])) control++;
|
|
177
|
+
if (control / win > CONTROL_SHARE_MAX) return null;
|
|
178
|
+
const d = decodeUtf8Strict(s);
|
|
179
|
+
if (!d.ok) return null;
|
|
180
|
+
return { encoding: "utf8", text: finish(d.text), nulSubstituted: true };
|
|
181
|
+
}
|
|
182
|
+
function asciiReading(b) {
|
|
183
|
+
const out = new Uint8Array(b.length);
|
|
184
|
+
for (let i = 0; i < b.length; i++) {
|
|
185
|
+
const c = b[i];
|
|
186
|
+
out[i] = c >= 32 && c <= 126 || c === 9 || c === 10 || c === 13 ? c : 32;
|
|
187
|
+
}
|
|
188
|
+
return { encoding: "ascii", text: finish(Buffer.from(out).toString("latin1")), nulSubstituted: false };
|
|
189
|
+
}
|
|
190
|
+
var STRINGS_MIN_RUN = 8;
|
|
191
|
+
function stringsReading(b) {
|
|
192
|
+
const runs = [];
|
|
193
|
+
let start = -1;
|
|
194
|
+
for (let i = 0; i <= b.length; i++) {
|
|
195
|
+
const printable = i < b.length && b[i] >= 32 && b[i] <= 126;
|
|
196
|
+
if (printable) {
|
|
197
|
+
if (start < 0) start = i;
|
|
198
|
+
} else if (start >= 0) {
|
|
199
|
+
if (i - start >= STRINGS_MIN_RUN) runs.push(Buffer.from(b.subarray(start, i)).toString("latin1"));
|
|
200
|
+
start = -1;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (runs.length === 0) return null;
|
|
204
|
+
return { encoding: "ascii", text: runs.join("\n"), nulSubstituted: false };
|
|
205
|
+
}
|
|
206
|
+
function withAscii(readings, b) {
|
|
207
|
+
const a = asciiReading(b);
|
|
208
|
+
return readings.some((r) => r.text === a.text) ? readings : [...readings, a];
|
|
209
|
+
}
|
|
210
|
+
function classifyFile(buffer) {
|
|
211
|
+
if (buffer.length === 0) return { kind: "text", texts: [{ encoding: "utf8", text: "", nulSubstituted: false }], stringsOnly: false };
|
|
212
|
+
if (!detectBinary(buffer)) {
|
|
213
|
+
const d = decodeUtf8Strict(buffer);
|
|
214
|
+
if (!d.ok) return { kind: "invalid-text", encoding: "utf8", reason: d.reason };
|
|
215
|
+
return { kind: "text", texts: [{ encoding: "utf8", text: finish(d.text), nulSubstituted: false }], stringsOnly: false };
|
|
216
|
+
}
|
|
217
|
+
const le = buffer[0] === 255 && buffer[1] === 254 && !(buffer[2] === 0 && buffer[3] === 0);
|
|
218
|
+
const be = buffer[0] === 254 && buffer[1] === 255;
|
|
219
|
+
if (le || be) {
|
|
220
|
+
const u = decodeUtf16(buffer, be);
|
|
221
|
+
if (!u) return { kind: "invalid-text", encoding: "utf16", reason: "UTF-16 with BOM, invalid (odd length or lone surrogate)" };
|
|
222
|
+
const bomReading = { encoding: be ? "utf16be" : "utf16le", text: finish(fromCharCodes(u)), nulSubstituted: false };
|
|
223
|
+
return { kind: "text", texts: withAscii([bomReading], buffer), stringsOnly: false };
|
|
224
|
+
}
|
|
225
|
+
const readings = [];
|
|
226
|
+
const parity = nulParity(buffer);
|
|
227
|
+
for (const order of ["le", "be"]) {
|
|
228
|
+
if (parity !== order) continue;
|
|
229
|
+
const u = decodeUtf16(buffer, order === "be");
|
|
230
|
+
if (u && plausibleUtf16(u)) {
|
|
231
|
+
readings.push({ encoding: order === "be" ? "utf16be" : "utf16le", text: finish(fromCharCodes(u)), nulSubstituted: false });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (readings.length === 0) {
|
|
235
|
+
const magic = isRealBinary(buffer);
|
|
236
|
+
if (magic) {
|
|
237
|
+
if (STRINGS_READABLE.has(magic.name)) return { kind: "text", texts: [asciiReading(buffer)], stringsOnly: true };
|
|
238
|
+
const strings = stringsReading(buffer);
|
|
239
|
+
return strings ? { kind: "binary", strings } : { kind: "binary" };
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const nulReading = nulSubstitutedReading(buffer);
|
|
243
|
+
if (nulReading) readings.push(nulReading);
|
|
244
|
+
if (readings.length === 0) return { kind: "unknown-binary" };
|
|
245
|
+
return { kind: "text", texts: withAscii(readings, buffer), stringsOnly: false };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// src/core/ignore.ts
|
|
249
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
250
|
+
import { Minimatch } from "minimatch";
|
|
251
|
+
|
|
252
|
+
// ../shared/dist/constants.js
|
|
253
|
+
var SEVERITY_WEIGHTS = {
|
|
254
|
+
info: 1,
|
|
255
|
+
low: 5,
|
|
256
|
+
medium: 15,
|
|
257
|
+
high: 30,
|
|
258
|
+
critical: 50
|
|
259
|
+
};
|
|
260
|
+
var EXIT_CODES = {
|
|
261
|
+
SAFE: 0,
|
|
262
|
+
BLOCKED: 1,
|
|
263
|
+
CONFIG_ERROR: 2,
|
|
264
|
+
RUNTIME_ERROR: 3
|
|
265
|
+
};
|
|
266
|
+
var DEFAULT_POLICY_PATH = "shipguard.policy.yml";
|
|
267
|
+
var DEFAULT_REPORT_DIR = ".shipguard/reports";
|
|
268
|
+
var DEFAULT_REPORT_FILE = ".shipguard/reports/latest.md";
|
|
269
|
+
var DEFAULT_HISTORY_PATH = ".shipguard/history.db";
|
|
270
|
+
var HISTORY_PATH_ENV_VAR = "SHIPGUARD_HISTORY_PATH";
|
|
271
|
+
var DEFAULT_REPO_ID_FALLBACK_PATH = ".shipguard/repo-id";
|
|
272
|
+
var DEFAULT_SCAN_ID_REUSE_WINDOW_MINUTES = 30;
|
|
273
|
+
var SCAN_ID_REUSE_WINDOW_ENV_VAR = "SHIPGUARD_SCAN_ID_REUSE_WINDOW_MINUTES";
|
|
274
|
+
|
|
275
|
+
// src/core/report.ts
|
|
276
|
+
import { mkdir, rename, writeFile } from "fs/promises";
|
|
277
|
+
import { dirname, basename, join } from "path";
|
|
278
|
+
import { randomUUID } from "crypto";
|
|
279
|
+
|
|
280
|
+
// src/core/verdict.ts
|
|
281
|
+
function computeVerdict(input) {
|
|
282
|
+
if (input.degraded === true) return "DO_NOT_SHIP";
|
|
283
|
+
const score = input.riskScore.score;
|
|
284
|
+
if (score <= 20) return "SAFE_TO_SHIP";
|
|
285
|
+
if (score < 50) return "REVIEW_BEFORE_SHIP";
|
|
286
|
+
return "DO_NOT_SHIP";
|
|
287
|
+
}
|
|
288
|
+
function applyVerdict(result) {
|
|
289
|
+
const verdict = computeVerdict({
|
|
290
|
+
riskScore: result.riskScore,
|
|
291
|
+
degraded: result.degraded
|
|
292
|
+
});
|
|
293
|
+
result.recommendation = verdict;
|
|
294
|
+
result.riskScore.recommendation = verdict;
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
function effectiveRecommendation(result) {
|
|
298
|
+
return result.recommendation ?? result.riskScore.recommendation;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// src/core/report.ts
|
|
302
|
+
function severitySection(title, findings) {
|
|
303
|
+
if (findings.length === 0) {
|
|
304
|
+
return `## ${title}
|
|
305
|
+
|
|
306
|
+
None
|
|
307
|
+
`;
|
|
308
|
+
}
|
|
309
|
+
const entries = findings.map((f) => {
|
|
310
|
+
const lines = [`### ${f.title}`];
|
|
311
|
+
lines.push(`- **File:** ${f.file}${f.line != null ? `:${f.line}` : ""}`);
|
|
312
|
+
lines.push(`- **Severity:** ${f.severity}`);
|
|
313
|
+
if (f.evidence != null) lines.push(`- **Evidence:** \`${f.evidence}\``);
|
|
314
|
+
lines.push(`- **Explanation:** ${f.explanation}`);
|
|
315
|
+
lines.push(`- **Recommendation:** ${f.recommendation}`);
|
|
316
|
+
return lines.join("\n");
|
|
317
|
+
});
|
|
318
|
+
return `## ${title}
|
|
319
|
+
|
|
320
|
+
${entries.join("\n\n")}
|
|
321
|
+
`;
|
|
322
|
+
}
|
|
323
|
+
function buildFixOrder(findings) {
|
|
324
|
+
const blocking = findings.filter((f) => f.blocking);
|
|
325
|
+
const nonBlocking = findings.filter((f) => !f.blocking);
|
|
326
|
+
const severityOrder = ["critical", "high", "medium", "low", "info"];
|
|
327
|
+
const sorted = [
|
|
328
|
+
...blocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity)),
|
|
329
|
+
...nonBlocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity))
|
|
330
|
+
];
|
|
331
|
+
if (sorted.length === 0) return "No findings to address.\n";
|
|
332
|
+
return sorted.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}${f.blocking ? " \u{1F6D1} blocking" : ""}`).join("\n");
|
|
333
|
+
}
|
|
334
|
+
function attitudeLine(recommendation, degraded) {
|
|
335
|
+
if (degraded) return "INCOMPLETE \u2014 parts of this scan did not run, so it cannot say this is safe.";
|
|
336
|
+
if (recommendation === "SAFE_TO_SHIP") return "SHIP IT \u2014 nothing blocking. Go make something people want.";
|
|
337
|
+
if (recommendation === "DO_NOT_SHIP") return "BLOCKED \u2014 shipping this would hurt. Fix the criticals first.";
|
|
338
|
+
return `HOLD UP \u2014 findings need eyes before this ships.`;
|
|
339
|
+
}
|
|
340
|
+
function topThreeFindings(findings) {
|
|
341
|
+
const severityOrder = ["critical", "high", "medium", "low", "info"];
|
|
342
|
+
const sorted = [...findings].sort((a, b) => {
|
|
343
|
+
if (a.blocking !== b.blocking) return a.blocking ? -1 : 1;
|
|
344
|
+
return severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity);
|
|
345
|
+
});
|
|
346
|
+
const top = sorted.slice(0, 3);
|
|
347
|
+
if (top.length === 0) return "None \u2014 clean scan.\n";
|
|
348
|
+
return top.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}`).join("\n");
|
|
349
|
+
}
|
|
350
|
+
function severityBreakdownTable(riskScore) {
|
|
351
|
+
const rows = [
|
|
352
|
+
["Critical", riskScore.criticalCount],
|
|
353
|
+
["High", riskScore.highCount],
|
|
354
|
+
["Medium", riskScore.mediumCount],
|
|
355
|
+
["Low", riskScore.lowCount],
|
|
356
|
+
["Info", riskScore.infoCount]
|
|
357
|
+
];
|
|
358
|
+
const lines = ["| Severity | Count |", "|----------|-------|"];
|
|
359
|
+
for (const [label, count] of rows) {
|
|
360
|
+
lines.push(`| ${label} | ${count} |`);
|
|
361
|
+
}
|
|
362
|
+
return lines.join("\n");
|
|
363
|
+
}
|
|
364
|
+
function buildUserMarkdown(result, elapsedMs) {
|
|
365
|
+
const { riskScore, findings, filesScanned, timestamp } = result;
|
|
366
|
+
const rec = effectiveRecommendation(result);
|
|
367
|
+
const degraded = result.degraded === true;
|
|
368
|
+
const elapsedStr = elapsedMs != null ? elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s` : "N/A";
|
|
369
|
+
const critical = findings.filter((f) => f.severity === "critical");
|
|
370
|
+
const high = findings.filter((f) => f.severity === "high");
|
|
371
|
+
const medium = findings.filter((f) => f.severity === "medium");
|
|
372
|
+
const low = findings.filter((f) => f.severity === "low");
|
|
373
|
+
const sections = [
|
|
374
|
+
"# ShipGuard Release Report",
|
|
375
|
+
"",
|
|
376
|
+
"## SUMMARY",
|
|
377
|
+
"",
|
|
378
|
+
`**Verdict:** ${rec} \u2014 ${attitudeLine(rec, degraded)}`,
|
|
379
|
+
"",
|
|
380
|
+
`**Files scanned:** ${filesScanned} | **Elapsed:** ${elapsedStr} | **Generated:** ${timestamp}`,
|
|
381
|
+
"",
|
|
382
|
+
...degraded ? [
|
|
383
|
+
"### Why this scan is incomplete",
|
|
384
|
+
"",
|
|
385
|
+
...(result.degradedReasons ?? []).length > 0 ? (result.degradedReasons ?? []).map((r) => `- \`${r.code}\`${r.detail ? ` \u2014 ${r.detail}` : ""}`) : ["- Reason not recorded \u2014 see `degraded` in the JSON report."],
|
|
386
|
+
""
|
|
387
|
+
] : [],
|
|
388
|
+
"### Severity Breakdown",
|
|
389
|
+
"",
|
|
390
|
+
severityBreakdownTable(riskScore),
|
|
391
|
+
"",
|
|
392
|
+
`**Risk Score:** ${riskScore.score}/100 | **Total Findings:** ${riskScore.totalFindings}`,
|
|
393
|
+
"",
|
|
394
|
+
"### Top 3 Things to Fix",
|
|
395
|
+
"",
|
|
396
|
+
topThreeFindings(findings),
|
|
397
|
+
"",
|
|
398
|
+
"---",
|
|
399
|
+
"",
|
|
400
|
+
severitySection("Critical Findings", critical),
|
|
401
|
+
severitySection("High Findings", high),
|
|
402
|
+
severitySection("Medium Findings", medium),
|
|
403
|
+
severitySection("Low Findings", low),
|
|
404
|
+
"## Suggested Fix Order",
|
|
405
|
+
"",
|
|
406
|
+
buildFixOrder(findings),
|
|
407
|
+
"",
|
|
408
|
+
"## Final Recommendation",
|
|
409
|
+
"",
|
|
410
|
+
`**${rec}**`,
|
|
411
|
+
""
|
|
412
|
+
];
|
|
413
|
+
return sections.join("\n");
|
|
414
|
+
}
|
|
415
|
+
function buildAgentJson(result) {
|
|
416
|
+
const publicResult = { ...result };
|
|
417
|
+
delete publicResult._skippedTooLarge;
|
|
418
|
+
delete publicResult._skippedBinary;
|
|
419
|
+
delete publicResult._truncated;
|
|
420
|
+
return JSON.stringify(publicResult, null, 2);
|
|
421
|
+
}
|
|
422
|
+
var RUNS_SUBDIR = "runs";
|
|
423
|
+
async function writeAtomic(path, content) {
|
|
424
|
+
const tmp = `${path}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
|
|
425
|
+
await writeFile(tmp, content, "utf-8");
|
|
426
|
+
await rename(tmp, path);
|
|
427
|
+
}
|
|
428
|
+
async function generateReport(result, outputPath, elapsedMs) {
|
|
429
|
+
const dir = dirname(outputPath);
|
|
430
|
+
const base = basename(outputPath, ".md");
|
|
431
|
+
const jsonPath = join(dir, `${base}.json`);
|
|
432
|
+
const runId = sanitizeRunId(result.runId) ?? `run-${Date.now()}`;
|
|
433
|
+
const runMdName = join(RUNS_SUBDIR, `${runId}.md`);
|
|
434
|
+
const runJsonName = join(RUNS_SUBDIR, `${runId}.json`);
|
|
435
|
+
const runMdPath = join(dir, runMdName);
|
|
436
|
+
const runJsonPath = join(dir, runJsonName);
|
|
437
|
+
const mdContent = buildUserMarkdown(result, elapsedMs);
|
|
438
|
+
const jsonContent = buildAgentJson(result);
|
|
439
|
+
const pointer = {
|
|
440
|
+
pointer: true,
|
|
441
|
+
pointerVersion: 1,
|
|
442
|
+
runId,
|
|
443
|
+
timestamp: result.timestamp,
|
|
444
|
+
recommendation: effectiveRecommendation(result),
|
|
445
|
+
runJson: runJsonName,
|
|
446
|
+
runMarkdown: runMdName
|
|
447
|
+
};
|
|
448
|
+
await mkdir(dir, { recursive: true });
|
|
449
|
+
await mkdir(join(dir, RUNS_SUBDIR), { recursive: true });
|
|
450
|
+
await Promise.all([
|
|
451
|
+
writeAtomic(runMdPath, mdContent),
|
|
452
|
+
writeAtomic(runJsonPath, jsonContent)
|
|
453
|
+
]);
|
|
454
|
+
await Promise.all([
|
|
455
|
+
writeAtomic(outputPath, mdContent),
|
|
456
|
+
writeAtomic(jsonPath, JSON.stringify(pointer, null, 2) + "\n")
|
|
457
|
+
]);
|
|
458
|
+
return { mdPath: outputPath, jsonPath, runMdPath, runJsonPath };
|
|
459
|
+
}
|
|
460
|
+
function sanitizeRunId(runId) {
|
|
461
|
+
if (!runId) return void 0;
|
|
462
|
+
const safe = runId.replace(/[^A-Za-z0-9._-]/g, "");
|
|
463
|
+
return safe.length > 0 && safe !== "." && safe !== ".." ? safe.slice(0, 96) : void 0;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// src/core/ignore.ts
|
|
467
|
+
var DEFAULT_IGNORE = [
|
|
468
|
+
"node_modules/**",
|
|
469
|
+
"dist/**",
|
|
470
|
+
"build/**",
|
|
471
|
+
".next/**",
|
|
472
|
+
"coverage/**",
|
|
473
|
+
".git/**",
|
|
474
|
+
"*.lock",
|
|
475
|
+
"pnpm-lock.yaml",
|
|
476
|
+
"package-lock.json",
|
|
477
|
+
".cache/**",
|
|
478
|
+
".turbo/**",
|
|
479
|
+
".venv/**",
|
|
480
|
+
"venv/**",
|
|
481
|
+
"vendor/**",
|
|
482
|
+
"tmp/**",
|
|
483
|
+
"out/**",
|
|
484
|
+
"*.log",
|
|
485
|
+
"*.min.js",
|
|
486
|
+
"*.map",
|
|
487
|
+
".DS_Store",
|
|
488
|
+
// ShipGuard's own report output: never scan the tool's own artifacts
|
|
489
|
+
".shipguard/**"
|
|
490
|
+
];
|
|
491
|
+
function selfArtifactIgnorePatterns(policy) {
|
|
492
|
+
const patterns = [];
|
|
493
|
+
const add = (p) => {
|
|
494
|
+
if (!p) return;
|
|
495
|
+
if (p.startsWith("/")) return;
|
|
496
|
+
const rel = p.replace(/^\.\//, "");
|
|
497
|
+
if (!rel) return;
|
|
498
|
+
patterns.push(rel);
|
|
499
|
+
};
|
|
500
|
+
const reportOutput = policy.report?.output;
|
|
501
|
+
add(reportOutput);
|
|
502
|
+
if (reportOutput) {
|
|
503
|
+
add(reportOutput.replace(/\.md$/, ".json"));
|
|
504
|
+
const reportDir = dirname2(reportOutput);
|
|
505
|
+
add(join2(reportDir === "." ? "" : reportDir, RUNS_SUBDIR, "**"));
|
|
506
|
+
}
|
|
507
|
+
add(policy.history?.path);
|
|
508
|
+
add(process.env[HISTORY_PATH_ENV_VAR]);
|
|
509
|
+
return patterns;
|
|
510
|
+
}
|
|
511
|
+
function buildIgnoreRules(policy) {
|
|
512
|
+
const defaults = [.../* @__PURE__ */ new Set([...DEFAULT_IGNORE, ...selfArtifactIgnorePatterns(policy)])];
|
|
513
|
+
const isDefault = new Set(defaults);
|
|
514
|
+
const user = [...new Set(policy.ignore?.paths ?? [])].filter((p) => !isDefault.has(p));
|
|
515
|
+
return [
|
|
516
|
+
...defaults.map((pattern) => ({ pattern, by: "default" })),
|
|
517
|
+
...user.map((pattern) => ({ pattern, by: "user" }))
|
|
518
|
+
];
|
|
519
|
+
}
|
|
520
|
+
function isDirectoryRule(pattern) {
|
|
521
|
+
return pattern.endsWith("/**") && !/[*?[\]{}!()]/.test(pattern.slice(0, -3));
|
|
522
|
+
}
|
|
523
|
+
function classifyIgnored(relPath, rules) {
|
|
524
|
+
const parts = relPath.split("/");
|
|
525
|
+
const prefixes = [];
|
|
526
|
+
for (let i = 1; i <= parts.length; i++) prefixes.push(parts.slice(0, i).join("/"));
|
|
527
|
+
for (const rule of rules) {
|
|
528
|
+
const matcher = compiled(rule.pattern);
|
|
529
|
+
for (const candidate of prefixes) {
|
|
530
|
+
if (matcher.match(candidate)) return rule;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
var matcherCache = /* @__PURE__ */ new Map();
|
|
536
|
+
function compiled(pattern) {
|
|
537
|
+
let m = matcherCache.get(pattern);
|
|
538
|
+
if (!m) {
|
|
539
|
+
m = new Minimatch(pattern.replace(/^\.\//, ""), { dot: true });
|
|
540
|
+
matcherCache.set(pattern, m);
|
|
541
|
+
}
|
|
542
|
+
return m;
|
|
543
|
+
}
|
|
544
|
+
function isShipguardArtifactPath(rel) {
|
|
545
|
+
return rel.split("/").slice(0, -1).includes(".shipguard");
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/utils/fs.ts
|
|
549
|
+
var DEFAULT_MAX_FILE_SIZE_BYTES = 512 * 1024;
|
|
550
|
+
var DEFAULT_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
|
|
551
|
+
var DEFAULT_MAX_FILES = 5e3;
|
|
552
|
+
var MAX_SKIPPED_NAMES = 50;
|
|
553
|
+
function createReadState() {
|
|
554
|
+
return {
|
|
555
|
+
files: [],
|
|
556
|
+
acceptedPaths: 0,
|
|
557
|
+
skippedTooLarge: 0,
|
|
558
|
+
skippedTooLargeFiles: [],
|
|
559
|
+
skippedBinary: 0,
|
|
560
|
+
skippedBinaryFiles: [],
|
|
561
|
+
skippedBinaryHeadOnly: 0,
|
|
562
|
+
skippedUnknownBinary: 0,
|
|
563
|
+
skippedUnknownBinaryFiles: [],
|
|
564
|
+
skippedSpecial: 0,
|
|
565
|
+
skippedSpecialFiles: [],
|
|
566
|
+
skippedSymlinks: 0,
|
|
567
|
+
skippedSymlinkFiles: [],
|
|
568
|
+
nulSubstituted: 0,
|
|
569
|
+
nulSubstitutedFiles: [],
|
|
570
|
+
utf16Decoded: 0,
|
|
571
|
+
multiReading: 0,
|
|
572
|
+
asciiStrings: 0,
|
|
573
|
+
binaryStringsScanned: 0,
|
|
574
|
+
selfArtifacts: 0,
|
|
575
|
+
selfArtifactFiles: [],
|
|
576
|
+
truncated: false,
|
|
577
|
+
notReached: 0,
|
|
578
|
+
discovered: 0,
|
|
579
|
+
ignoredByDefault: [],
|
|
580
|
+
ignoredByUser: 0,
|
|
581
|
+
invalidUtf8Files: [],
|
|
582
|
+
unreadableFiles: [],
|
|
583
|
+
unaddressableCount: 0,
|
|
584
|
+
bytesRead: 0
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
function pushName(list, name) {
|
|
588
|
+
if (list.length < MAX_SKIPPED_NAMES) list.push(name);
|
|
589
|
+
}
|
|
590
|
+
async function readHead(path) {
|
|
591
|
+
const fh = await open(path, "r");
|
|
592
|
+
try {
|
|
593
|
+
const buf = Buffer.alloc(HEAD_BYTES);
|
|
594
|
+
const { bytesRead } = await fh.read(buf, 0, HEAD_BYTES, 0);
|
|
595
|
+
return buf.subarray(0, bytesRead);
|
|
596
|
+
} finally {
|
|
597
|
+
await fh.close();
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
function capReached(state, limits) {
|
|
601
|
+
if (state.acceptedPaths >= limits.maxFiles) return "maxFiles";
|
|
602
|
+
if (state.bytesRead >= limits.maxTotalBytes) return "maxTotalBytes";
|
|
603
|
+
return null;
|
|
604
|
+
}
|
|
605
|
+
function isShipguardOnlyGitignore(buffer) {
|
|
606
|
+
const lines = buffer.toString("utf8").split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
|
|
607
|
+
return lines.length > 0 && lines.every((l) => l === ".shipguard/" || l === ".shipguard");
|
|
608
|
+
}
|
|
609
|
+
async function readCandidate(state, c, maxFileSizeBytes) {
|
|
610
|
+
try {
|
|
611
|
+
const fileStat = await stat(c.readPath);
|
|
612
|
+
if (fileStat.size > maxFileSizeBytes) {
|
|
613
|
+
const head = await readHead(c.readPath);
|
|
614
|
+
if (headLooksLikeRealBinary(head)) {
|
|
615
|
+
state.skippedBinary++;
|
|
616
|
+
state.skippedBinaryHeadOnly++;
|
|
617
|
+
pushName(state.skippedBinaryFiles, c.rel);
|
|
618
|
+
} else {
|
|
619
|
+
state.skippedTooLarge++;
|
|
620
|
+
pushName(state.skippedTooLargeFiles, c.rel);
|
|
621
|
+
}
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
const buffer = await readFile(c.readPath);
|
|
625
|
+
if ((c.rel === ".gitignore" || c.rel.endsWith("/.gitignore")) && isShipguardOnlyGitignore(buffer)) {
|
|
626
|
+
state.selfArtifacts++;
|
|
627
|
+
pushName(state.selfArtifactFiles, c.rel);
|
|
628
|
+
state.discovered = Math.max(0, state.discovered - 1);
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
const result = classifyFile(new Uint8Array(buffer));
|
|
632
|
+
switch (result.kind) {
|
|
633
|
+
case "binary":
|
|
634
|
+
state.skippedBinary++;
|
|
635
|
+
pushName(state.skippedBinaryFiles, c.rel);
|
|
636
|
+
if (result.strings) {
|
|
637
|
+
state.files.push({ path: c.path, content: result.strings.text, relativePath: c.rel });
|
|
638
|
+
state.binaryStringsScanned++;
|
|
639
|
+
state.bytesRead += buffer.length;
|
|
640
|
+
}
|
|
641
|
+
return;
|
|
642
|
+
case "unknown-binary":
|
|
643
|
+
state.skippedUnknownBinary++;
|
|
644
|
+
pushName(state.skippedUnknownBinaryFiles, c.rel);
|
|
645
|
+
return;
|
|
646
|
+
case "invalid-text":
|
|
647
|
+
state.invalidUtf8Files.push({ relativePath: c.rel, reason: result.reason });
|
|
648
|
+
return;
|
|
649
|
+
case "text": {
|
|
650
|
+
for (const reading of result.texts) {
|
|
651
|
+
state.files.push({ path: c.path, content: reading.text, relativePath: c.rel });
|
|
652
|
+
}
|
|
653
|
+
state.acceptedPaths++;
|
|
654
|
+
state.bytesRead += buffer.length;
|
|
655
|
+
const nonAscii = result.texts.filter((t) => t.encoding !== "ascii");
|
|
656
|
+
if (result.texts.some((t) => t.encoding === "utf16le" || t.encoding === "utf16be")) state.utf16Decoded++;
|
|
657
|
+
if (result.texts.some((t) => t.nulSubstituted)) {
|
|
658
|
+
state.nulSubstituted++;
|
|
659
|
+
pushName(state.nulSubstitutedFiles, c.rel);
|
|
660
|
+
}
|
|
661
|
+
if (nonAscii.length >= 2) state.multiReading++;
|
|
662
|
+
if (result.stringsOnly) state.asciiStrings++;
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
} catch (err) {
|
|
667
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
668
|
+
logger.warn(`[shipguard] Could not read file ${c.rel}: ${detail}`);
|
|
669
|
+
state.unreadableFiles.push(c.rel);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
async function resolveUndecodableNames(rootDir, paths) {
|
|
673
|
+
const kept = [];
|
|
674
|
+
const bad = [];
|
|
675
|
+
const checked = /* @__PURE__ */ new Map();
|
|
676
|
+
for (const p of paths) {
|
|
677
|
+
if (!p.includes("\uFFFD")) {
|
|
678
|
+
kept.push(p);
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
const segs = p.split("/");
|
|
682
|
+
let prefix = "";
|
|
683
|
+
let drop = false;
|
|
684
|
+
for (const seg of segs) {
|
|
685
|
+
const display = prefix + seg;
|
|
686
|
+
if (seg.includes("\uFFFD")) {
|
|
687
|
+
let validExists = checked.get(display);
|
|
688
|
+
if (validExists === void 0) {
|
|
689
|
+
validExists = false;
|
|
690
|
+
try {
|
|
691
|
+
const names = await readdir(join3(rootDir, prefix), { encoding: "buffer" });
|
|
692
|
+
for (const raw of names) {
|
|
693
|
+
if (raw.toString("utf8") !== seg) continue;
|
|
694
|
+
if (decodeUtf8Strict(raw).ok) validExists = true;
|
|
695
|
+
else bad.push(display);
|
|
696
|
+
}
|
|
697
|
+
} catch (err) {
|
|
698
|
+
logger.warn(`[shipguard] Could not list ${prefix || "."} to verify file names: ${err instanceof Error ? err.message : String(err)}`);
|
|
699
|
+
bad.push(display);
|
|
700
|
+
}
|
|
701
|
+
checked.set(display, validExists);
|
|
702
|
+
}
|
|
703
|
+
if (!validExists) {
|
|
704
|
+
drop = true;
|
|
705
|
+
break;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
prefix = display + "/";
|
|
709
|
+
}
|
|
710
|
+
if (!drop) kept.push(p);
|
|
711
|
+
}
|
|
712
|
+
return { kept, bad };
|
|
713
|
+
}
|
|
714
|
+
async function recoverUnenteredDirs(rootDir, entries, patterns, isDefaultIgnored) {
|
|
715
|
+
const out = [];
|
|
716
|
+
const bad = [];
|
|
717
|
+
const visit = async (base, list) => {
|
|
718
|
+
const parents = /* @__PURE__ */ new Set();
|
|
719
|
+
for (const e of list) {
|
|
720
|
+
const i = e.path.lastIndexOf("/");
|
|
721
|
+
if (i > 0) parents.add(e.path.slice(0, i));
|
|
722
|
+
}
|
|
723
|
+
for (const e of list) {
|
|
724
|
+
if (!e.dirent.isDirectory() || e.path.includes("\uFFFD") || parents.has(e.path)) continue;
|
|
725
|
+
const rel = base ? `${base}/${e.path}` : e.path;
|
|
726
|
+
if (isDefaultIgnored(rel)) continue;
|
|
727
|
+
let sub;
|
|
728
|
+
try {
|
|
729
|
+
sub = await fg(patterns, {
|
|
730
|
+
cwd: join3(rootDir, rel),
|
|
731
|
+
dot: true,
|
|
732
|
+
absolute: false,
|
|
733
|
+
onlyFiles: false,
|
|
734
|
+
followSymbolicLinks: false,
|
|
735
|
+
objectMode: true
|
|
736
|
+
});
|
|
737
|
+
} catch (err) {
|
|
738
|
+
logger.warn(`[shipguard] Could not list folder ${rel}: ${err instanceof Error ? err.message : String(err)}`);
|
|
739
|
+
bad.push(rel);
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
742
|
+
const prefixed = sub.map((s) => ({ path: `${rel}/${s.path}`, dirent: s.dirent })).filter((s) => !isDefaultIgnored(s.path));
|
|
743
|
+
out.push(...prefixed);
|
|
744
|
+
await visit(rel, sub);
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
await visit("", entries);
|
|
748
|
+
return { entries: out, bad };
|
|
749
|
+
}
|
|
750
|
+
async function countIgnored(rootDir, rules) {
|
|
751
|
+
const defaults = rules.filter((r) => r.by === "default");
|
|
752
|
+
const dirRules = defaults.filter((r) => isDirectoryRule(r.pattern));
|
|
753
|
+
const fileRules = defaults.filter((r) => !isDirectoryRule(r.pattern));
|
|
754
|
+
const dirPatterns = dirRules.map((r) => r.pattern);
|
|
755
|
+
const ignoredByDefault = [];
|
|
756
|
+
for (const r of dirRules) {
|
|
757
|
+
try {
|
|
758
|
+
const st = await stat(join3(rootDir, r.pattern.slice(0, -3)));
|
|
759
|
+
if (st.isDirectory()) ignoredByDefault.push({ pattern: r.pattern, present: true });
|
|
760
|
+
} catch (err) {
|
|
761
|
+
const code = err.code;
|
|
762
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
763
|
+
logger.warn(`[shipguard] Could not check ignored folder ${r.pattern}: ${err instanceof Error ? err.message : String(err)}`);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (fileRules.length > 0) {
|
|
768
|
+
const hits = await fg(fileRules.map((r) => r.pattern), {
|
|
769
|
+
cwd: rootDir,
|
|
770
|
+
dot: true,
|
|
771
|
+
onlyFiles: true,
|
|
772
|
+
followSymbolicLinks: false,
|
|
773
|
+
ignore: dirPatterns
|
|
774
|
+
});
|
|
775
|
+
const counts = /* @__PURE__ */ new Map();
|
|
776
|
+
for (const h of hits) {
|
|
777
|
+
const rule = classifyIgnored(h, fileRules);
|
|
778
|
+
if (rule) counts.set(rule.pattern, (counts.get(rule.pattern) ?? 0) + 1);
|
|
779
|
+
}
|
|
780
|
+
for (const r of fileRules) {
|
|
781
|
+
const files = counts.get(r.pattern);
|
|
782
|
+
if (files) ignoredByDefault.push({ pattern: r.pattern, files });
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
return { ignoredByDefault };
|
|
786
|
+
}
|
|
787
|
+
function compareScanPaths(a, b) {
|
|
788
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
789
|
+
}
|
|
790
|
+
async function readFiles(rootDir, patterns = ["**/*"], ignorePatterns = [], options = {}) {
|
|
791
|
+
const maxFileSizeBytes = options.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES;
|
|
792
|
+
const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES;
|
|
793
|
+
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
|
794
|
+
const { onProgress } = options;
|
|
795
|
+
const rules = options.ignoreRules ?? [
|
|
796
|
+
...DEFAULT_IGNORE.map((pattern) => ({ pattern, by: "default" })),
|
|
797
|
+
...ignorePatterns.map((pattern) => ({ pattern, by: "user" }))
|
|
798
|
+
];
|
|
799
|
+
const defaultRules = rules.filter((r) => r.by === "default");
|
|
800
|
+
const userRules = rules.filter((r) => r.by === "user");
|
|
801
|
+
const allIgnore = defaultRules.map((r) => r.pattern);
|
|
802
|
+
const notUserIgnored = (p) => userRules.length === 0 || classifyIgnored(p, userRules) === null;
|
|
803
|
+
const listedAll = await fg(patterns, {
|
|
804
|
+
cwd: rootDir,
|
|
805
|
+
ignore: allIgnore,
|
|
806
|
+
dot: true,
|
|
807
|
+
absolute: false,
|
|
808
|
+
onlyFiles: true,
|
|
809
|
+
// Privacy moat: NEVER follow symlinks. A symlink inside the project pointing out of the root
|
|
810
|
+
// (e.g. `ln -s /home escape`) would otherwise cause the scan to descend out-of-tree. fast-glob
|
|
811
|
+
// defaults this to true, so it is load-bearing that we set it false explicitly.
|
|
812
|
+
followSymbolicLinks: false
|
|
813
|
+
});
|
|
814
|
+
const probeAll = await fg(patterns, {
|
|
815
|
+
cwd: rootDir,
|
|
816
|
+
ignore: allIgnore,
|
|
817
|
+
dot: true,
|
|
818
|
+
absolute: false,
|
|
819
|
+
onlyFiles: false,
|
|
820
|
+
followSymbolicLinks: false,
|
|
821
|
+
objectMode: true
|
|
822
|
+
});
|
|
823
|
+
const recovered = await recoverUnenteredDirs(rootDir, probeAll, patterns, (p) => classifyIgnored(p, defaultRules) !== null);
|
|
824
|
+
const extraFiles = recovered.entries.filter((e) => e.dirent.isFile()).map((e) => e.path);
|
|
825
|
+
const listedWithRecovered = [...listedAll, ...extraFiles];
|
|
826
|
+
const listedNoUser = listedWithRecovered.filter(notUserIgnored);
|
|
827
|
+
const listed = listedNoUser.filter((p) => !isShipguardArtifactPath(p));
|
|
828
|
+
const selfArtifactCount = listedNoUser.length - listed.length;
|
|
829
|
+
const named = await resolveUndecodableNames(rootDir, [...new Set(listed)]);
|
|
830
|
+
const filePaths = named.kept;
|
|
831
|
+
filePaths.sort(compareScanPaths);
|
|
832
|
+
const probeEntries = [...probeAll, ...recovered.entries].filter((e) => notUserIgnored(e.path) && !isShipguardArtifactPath(e.path));
|
|
833
|
+
const state = createReadState();
|
|
834
|
+
const symlinkPaths = probeEntries.filter((e) => e.dirent.isSymbolicLink()).map((e) => e.path).sort(compareScanPaths);
|
|
835
|
+
const specialPaths = probeEntries.filter((e) => e.dirent.isFIFO() || e.dirent.isSocket() || e.dirent.isCharacterDevice() || e.dirent.isBlockDevice()).map((e) => e.path).sort(compareScanPaths);
|
|
836
|
+
state.skippedSymlinks = symlinkPaths.length;
|
|
837
|
+
state.skippedSymlinkFiles = symlinkPaths.slice(0, MAX_SKIPPED_NAMES);
|
|
838
|
+
state.skippedSpecial = specialPaths.length;
|
|
839
|
+
state.skippedSpecialFiles = specialPaths.slice(0, MAX_SKIPPED_NAMES);
|
|
840
|
+
if (state.skippedSymlinks > 0) {
|
|
841
|
+
const names = state.skippedSymlinkFiles.join(", ");
|
|
842
|
+
const more = state.skippedSymlinks > state.skippedSymlinkFiles.length ? " (and others)" : "";
|
|
843
|
+
console.warn(
|
|
844
|
+
`[shipguard] Scan INCOMPLETE: ${state.skippedSymlinks} symlink(s) not followed (privacy protection) and NOT scanned: ${names}${more}`
|
|
845
|
+
);
|
|
846
|
+
}
|
|
847
|
+
const dirNames = probeEntries.filter((e) => e.dirent.isDirectory() && e.path.includes("\uFFFD")).map((e) => e.path);
|
|
848
|
+
const dirNamed = await resolveUndecodableNames(rootDir, [...new Set(dirNames)]);
|
|
849
|
+
const badAll = [.../* @__PURE__ */ new Set([...named.bad, ...dirNamed.bad, ...recovered.bad])].sort(compareScanPaths);
|
|
850
|
+
for (const display of badAll) {
|
|
851
|
+
state.unreadableFiles.push(display);
|
|
852
|
+
state.unaddressableCount++;
|
|
853
|
+
}
|
|
854
|
+
const counted = await countIgnored(rootDir, rules);
|
|
855
|
+
state.ignoredByDefault = counted.ignoredByDefault;
|
|
856
|
+
state.ignoredByUser = listedWithRecovered.length - listedNoUser.length;
|
|
857
|
+
state.selfArtifacts += selfArtifactCount;
|
|
858
|
+
for (const p of listedNoUser) if (isShipguardArtifactPath(p)) pushName(state.selfArtifactFiles, p);
|
|
859
|
+
const total = filePaths.length;
|
|
860
|
+
state.discovered = total + state.skippedSymlinks + state.skippedSpecial + badAll.length;
|
|
861
|
+
let processed = 0;
|
|
862
|
+
for (let i = 0; i < filePaths.length; i++) {
|
|
863
|
+
const hit = capReached(state, { maxFiles, maxTotalBytes });
|
|
864
|
+
if (hit) {
|
|
865
|
+
state.truncated = true;
|
|
866
|
+
state.truncatedBy = hit;
|
|
867
|
+
state.notReached = total - i;
|
|
868
|
+
break;
|
|
869
|
+
}
|
|
870
|
+
const fp = filePaths[i];
|
|
871
|
+
await readCandidate(state, { readPath: join3(rootDir, fp), path: join3(rootDir, fp), rel: fp }, maxFileSizeBytes);
|
|
872
|
+
onProgress?.(++processed, total, fp);
|
|
873
|
+
}
|
|
874
|
+
return state;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
export {
|
|
878
|
+
SEVERITY_WEIGHTS,
|
|
879
|
+
EXIT_CODES,
|
|
880
|
+
DEFAULT_POLICY_PATH,
|
|
881
|
+
DEFAULT_REPORT_DIR,
|
|
882
|
+
DEFAULT_REPORT_FILE,
|
|
883
|
+
DEFAULT_HISTORY_PATH,
|
|
884
|
+
HISTORY_PATH_ENV_VAR,
|
|
885
|
+
DEFAULT_REPO_ID_FALLBACK_PATH,
|
|
886
|
+
DEFAULT_SCAN_ID_REUSE_WINDOW_MINUTES,
|
|
887
|
+
SCAN_ID_REUSE_WINDOW_ENV_VAR,
|
|
888
|
+
computeVerdict,
|
|
889
|
+
applyVerdict,
|
|
890
|
+
effectiveRecommendation,
|
|
891
|
+
generateReport,
|
|
892
|
+
buildIgnoreRules,
|
|
893
|
+
classifyIgnored,
|
|
894
|
+
isShipguardArtifactPath,
|
|
895
|
+
DEFAULT_MAX_FILE_SIZE_BYTES,
|
|
896
|
+
DEFAULT_MAX_TOTAL_BYTES,
|
|
897
|
+
DEFAULT_MAX_FILES,
|
|
898
|
+
MAX_SKIPPED_NAMES,
|
|
899
|
+
createReadState,
|
|
900
|
+
capReached,
|
|
901
|
+
readCandidate,
|
|
902
|
+
compareScanPaths,
|
|
903
|
+
readFiles
|
|
904
|
+
};
|