repometry 0.3.1 → 0.4.1

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.
Files changed (46) hide show
  1. package/package.json +1 -1
  2. package/target/main/resources/report/json/report-v2.schema.json +12 -1
  3. package/target/main/resources/viewer/files.css +6 -2
  4. package/target/main/ts/api/git/git.d.ts +1 -1
  5. package/target/main/ts/api/git/git.js +21 -5
  6. package/target/main/ts/api/git/inspection-source.d.ts +1 -1
  7. package/target/main/ts/api/git/inspection-source.js +10 -4
  8. package/target/main/ts/api/git/local.d.ts +1 -1
  9. package/target/main/ts/api/git/local.js +29 -10
  10. package/target/main/ts/api/worker/worker-protocol.js +34 -9
  11. package/target/main/ts/compose/analyze-snapshot.d.ts +1 -0
  12. package/target/main/ts/compose/analyze-snapshot.js +50 -17
  13. package/target/main/ts/compose/inspect.js +2 -2
  14. package/target/main/ts/compose/plugin-list.js +2 -1
  15. package/target/main/ts/compose/security-plugins.d.ts +1 -0
  16. package/target/main/ts/compose/security-plugins.js +7 -0
  17. package/target/main/ts/core/engine/manifest.js +3 -2
  18. package/target/main/ts/core/engine/plugin.d.ts +2 -0
  19. package/target/main/ts/core/model/line-coverage.d.ts +2 -0
  20. package/target/main/ts/core/model/line-coverage.js +19 -1
  21. package/target/main/ts/core/model/source.d.ts +3 -0
  22. package/target/main/ts/core/model/source.js +4 -1
  23. package/target/main/ts/core/usecases/inspect.js +2 -2
  24. package/target/main/ts/plugins/coverage/coverage.d.ts +4 -3
  25. package/target/main/ts/plugins/coverage/coverage.js +46 -17
  26. package/target/main/ts/plugins/language-js/js-security.d.ts +4 -0
  27. package/target/main/ts/plugins/language-js/js-security.js +508 -0
  28. package/target/main/ts/plugins/security/actions-security.d.ts +2 -0
  29. package/target/main/ts/plugins/security/actions-security.js +581 -0
  30. package/target/main/ts/plugins/security/dockerfile.d.ts +2 -0
  31. package/target/main/ts/plugins/security/dockerfile.js +488 -0
  32. package/target/main/ts/plugins/security/npm-supply-chain.d.ts +4 -0
  33. package/target/main/ts/plugins/security/npm-supply-chain.js +368 -0
  34. package/target/main/ts/plugins/security/secrets.d.ts +12 -0
  35. package/target/main/ts/plugins/security/secrets.js +254 -0
  36. package/target/main/ts/report/html/app/viewer-files.d.ts +7 -0
  37. package/target/main/ts/report/html/app/viewer-files.js +17 -3
  38. package/target/main/ts/report/html/app/viewer-filter.js +8 -0
  39. package/target/main/ts/report/html/app/viewer-source.d.ts +6 -0
  40. package/target/main/ts/report/html/app/viewer-source.js +34 -7
  41. package/target/main/ts/report/html/site/badges.d.ts +1 -4
  42. package/target/main/ts/report/html/site/badges.js +28 -19
  43. package/target/main/ts/report/json/projections/commit-summary.js +2 -11
  44. package/target/main/ts/report/json/projections/inspection-context.js +6 -12
  45. package/target/main/ts/report/json/projections/security-summary.d.ts +11 -0
  46. package/target/main/ts/report/json/projections/security-summary.js +22 -0
@@ -0,0 +1,368 @@
1
+ import { isRecord, pluginApi } from '../../core/engine/plugin.js';
2
+ import { findingResult } from '../../core/model/finding.js';
3
+ import { sourceFile } from '../../core/model/snapshot.js';
4
+ const tool = 'npm-supply-chain';
5
+ const ruleDescriptions = {
6
+ 'dependency-from-url': 'A package.json dependency is installed from a URL, git repository or tarball instead of a registry version.',
7
+ 'dependency-unbounded': 'A package.json dependency accepts any version through "*", "latest" or an empty range.',
8
+ 'install-script': 'A package.json declares a preinstall, install or postinstall script that runs whenever the package is installed.',
9
+ 'lockfile-insecure-registry': 'A lockfile resolves a package over unencrypted HTTP or git transport.',
10
+ 'lockfile-foreign-host': 'A lockfile resolves a package from a host other than the public npm or Yarn registry.',
11
+ 'lockfile-missing-integrity': 'A package-lock entry resolved from a registry has no integrity hash.',
12
+ };
13
+ /** Above this many hits of one rule in one file, the rest collapse into a single summary finding. */
14
+ export const findingsPerRule = 20;
15
+ const registryHosts = new Set(['registry.npmjs.org', 'registry.yarnpkg.com']);
16
+ const insecureProtocols = new Set(['http', 'git', 'git+http']);
17
+ const dependencySections = ['dependencies', 'devDependencies', 'optionalDependencies'];
18
+ const installScripts = ['preinstall', 'install', 'postinstall'];
19
+ const levelOrder = ['low', 'medium', 'high'];
20
+ /** A repository page URL such as https://github.com/owner/repo, which npm clones with git. */
21
+ const hostedRepository = /^https:\/\/(?:www\.)?(?:github\.com|gitlab\.com|bitbucket\.org)\/[^/?#]+\/[^/?#]+\/?(?:#.*)?$/i;
22
+ export const npmSupplyChain = {
23
+ id: tool, version: '1.0.0', api: pluginApi,
24
+ kinds: ['security'],
25
+ claims: { globs: ['**/package.json', '**/package-lock.json', '**/npm-shrinkwrap.json', '**/yarn.lock', '**/pnpm-lock.yaml'] },
26
+ produces: [{ contract: findingResult.id, persistence: 'report' }],
27
+ rules: Object.entries(ruleDescriptions).map(([id, description]) => ({ id, category: 'dependency', description })),
28
+ operations: [{
29
+ id: 'scan', role: 'inspection', inputs: { source: sourceFile }, output: findingResult,
30
+ execute(inputs) {
31
+ const { path, bytes } = inputs.read('source', sourceFile);
32
+ if (path.split('/').includes('node_modules'))
33
+ return { measurements: [], findings: [] };
34
+ const name = path.slice(path.lastIndexOf('/') + 1);
35
+ const text = new TextDecoder().decode(bytes);
36
+ const hits = name === 'package.json' ? jsonHits(name, text, manifestHits)
37
+ : name === 'package-lock.json' || name === 'npm-shrinkwrap.json' ? jsonHits(name, text, packageLockHits)
38
+ : name === 'yarn.lock' ? yarnLockHits(text)
39
+ : name === 'pnpm-lock.yaml' ? pnpmLockHits(text) : [];
40
+ return { measurements: [], findings: capped(path, name, hits) };
41
+ },
42
+ }],
43
+ };
44
+ function capped(path, name, hits) {
45
+ const byLine = [...hits].sort((left, right) => (left.line ?? 0) - (right.line ?? 0));
46
+ const kept = [];
47
+ const summaries = [];
48
+ for (const rule of Object.keys(ruleDescriptions)) {
49
+ const matching = byLine.filter(hit => hit.rule === rule);
50
+ kept.push(...matching.slice(0, findingsPerRule));
51
+ const rest = matching.slice(findingsPerRule);
52
+ if (rest.length === 0)
53
+ continue;
54
+ const level = rest.reduce((worst, hit) => levelOrder.indexOf(hit.level) > levelOrder.indexOf(worst) ? hit.level : worst, 'low');
55
+ summaries.push({ tool, rule, category: 'dependency', level, path,
56
+ message: `${name} has ${matching.length} ${rule} findings; only the first ${findingsPerRule} are listed.` });
57
+ }
58
+ kept.sort((left, right) => (left.line ?? 0) - (right.line ?? 0));
59
+ return [...kept.map(({ rule, level, message, line, endLine }) => ({ tool, rule, category: 'dependency', level, message, path,
60
+ ...(line === undefined ? {} : { line, endLine: endLine ?? line }) })), ...summaries];
61
+ }
62
+ function jsonHits(name, text, analyse) {
63
+ let value;
64
+ try {
65
+ value = JSON.parse(text);
66
+ }
67
+ catch (error) {
68
+ throw new Error(`${name} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
69
+ }
70
+ const found = analyse(value);
71
+ if (found.length === 0)
72
+ return [];
73
+ const spans = locate(text, new Set(found.map(hit => pointer(hit.at))), Math.max(...found.map(hit => hit.at.length)));
74
+ return found.map(({ at, ...hit }) => ({ ...hit, ...spans.get(pointer(at)) }));
75
+ }
76
+ function manifestHits(manifest) {
77
+ if (!isRecord(manifest))
78
+ return [];
79
+ const hits = [];
80
+ for (const section of dependencySections) {
81
+ const dependencies = manifest[section];
82
+ if (!isRecord(dependencies))
83
+ continue;
84
+ for (const [name, spec] of Object.entries(dependencies)) {
85
+ if (typeof spec !== 'string')
86
+ continue;
87
+ const hit = specHit(name, spec.trim());
88
+ if (hit)
89
+ hits.push({ ...hit, at: [section, name] });
90
+ }
91
+ }
92
+ const scripts = isRecord(manifest.scripts) ? manifest.scripts : {};
93
+ const owner = typeof manifest.name === 'string' && manifest.name !== '' ? `Package ${manifest.name}` : 'This package';
94
+ for (const script of installScripts) {
95
+ const command = scripts[script];
96
+ if (typeof command !== 'string' || command.trim() === '')
97
+ continue;
98
+ hits.push({ rule: 'install-script', level: 'medium', at: ['scripts', script],
99
+ message: `${owner} runs a ${script} script on every install: ${JSON.stringify(abbreviate(command.trim(), 80))}.` });
100
+ }
101
+ return hits;
102
+ }
103
+ function specHit(name, spec) {
104
+ const alias = /^npm:(?:@[^/@\s]+\/)?[^/@\s]+(?:@(.*))?$/.exec(spec);
105
+ const range = alias ? (alias[1] ?? '').trim() : spec;
106
+ if (range === '' || range === '*' || range === 'latest') {
107
+ return { rule: 'dependency-unbounded', level: 'low',
108
+ message: `Dependency ${name} accepts any version (${range === '' ? 'empty range' : JSON.stringify(range)}).` };
109
+ }
110
+ if (alias)
111
+ return undefined;
112
+ const shown = display(spec);
113
+ const protocol = /^([a-z][a-z0-9+.-]*):\/\//i.exec(spec)?.[1]?.toLowerCase();
114
+ if (protocol === 'http') {
115
+ return { rule: 'dependency-from-url', level: 'high', message: `Dependency ${name} is downloaded over plain HTTP from ${shown}.` };
116
+ }
117
+ if (protocol === 'git' || protocol === 'git+http') {
118
+ return { rule: 'dependency-from-url', level: 'high',
119
+ message: `Dependency ${name} is fetched over unencrypted ${protocol}:// from ${shown}.` };
120
+ }
121
+ const git = protocol?.startsWith('git+') || /^(?:github|gitlab|bitbucket|gist):/i.test(spec)
122
+ || /^[\w.-]+@[\w.-]+:(?!\/\/)/.test(spec) || isGitHubShorthand(spec)
123
+ || (protocol === 'https' && (/\.git(?:#|$)/i.test(spec) || hostedRepository.test(spec)));
124
+ const tarball = !git && protocol === 'https';
125
+ if (!git && !tarball)
126
+ return undefined;
127
+ const commit = /#([0-9a-f]{40})$/i.exec(spec)?.[1]
128
+ ?? (tarball ? /^[^?#]*\/([0-9a-f]{40})(?:\.(?:tar\.gz|tgz|zip))?(?:[/?#]|$)/i.exec(spec)?.[1] : undefined);
129
+ if (commit) {
130
+ return { rule: 'dependency-from-url', level: 'low',
131
+ message: `Dependency ${name} bypasses the registry but is pinned to commit ${commit.slice(0, 12)} of ${shown}.` };
132
+ }
133
+ if (tarball && registryHosts.has(host(spec))) {
134
+ return { rule: 'dependency-from-url', level: 'low',
135
+ message: `Dependency ${name} names a registry tarball URL instead of a version range: ${shown}.` };
136
+ }
137
+ return { rule: 'dependency-from-url', level: 'high',
138
+ message: `Dependency ${name} follows ${git ? 'git source' : 'remote tarball'} ${shown} without a pinned commit.` };
139
+ }
140
+ /** npm reads `owner/repo` and `owner/repo#ref` as GitHub repositories; paths start with `.`, `/` or `~/`. */
141
+ function isGitHubShorthand(spec) {
142
+ return /^(?![.~])[^\s@:/#\\]+\/[^\s@:/#\\]+(?:#\S*)?$/.test(spec);
143
+ }
144
+ function packageLockHits(lock) {
145
+ if (!isRecord(lock) || !isRecord(lock.packages))
146
+ return [];
147
+ const hits = [];
148
+ for (const [key, entry] of Object.entries(lock.packages)) {
149
+ if (key === '' || !isRecord(entry) || entry.link === true || typeof entry.resolved !== 'string')
150
+ continue;
151
+ const marker = key.lastIndexOf('node_modules/');
152
+ const name = marker < 0 ? key : key.slice(marker + 'node_modules/'.length);
153
+ for (const { rule, level, says } of registryIssues(entry.resolved)) {
154
+ hits.push({ rule, level, message: `Package ${name} ${says}.`, at: ['packages', key, 'resolved'] });
155
+ }
156
+ const protocol = /^([a-z]+):\/\//i.exec(entry.resolved)?.[1]?.toLowerCase();
157
+ if ((protocol === 'https' || protocol === 'http') && (typeof entry.integrity !== 'string' || entry.integrity.trim() === '')) {
158
+ hits.push({ rule: 'lockfile-missing-integrity', level: 'medium', at: ['packages', key],
159
+ message: `Package ${name} resolves from ${host(entry.resolved)} without an integrity hash.` });
160
+ }
161
+ }
162
+ return hits;
163
+ }
164
+ function yarnLockHits(text) {
165
+ const hits = [];
166
+ let name;
167
+ for (const [index, line] of text.split(/\r?\n/).entries()) {
168
+ if (line.trim() === '' || line.startsWith('#'))
169
+ continue;
170
+ if (!/^\s/.test(line)) {
171
+ name = line.endsWith(':') && !line.startsWith('__metadata') ? selectorName(line.slice(0, -1)) : undefined;
172
+ continue;
173
+ }
174
+ const field = name === undefined ? null : /^ {2}(?:resolved|resolution:)\s+(.+?)\s*$/.exec(line);
175
+ const url = field ? urlIn(unquote(field[1])) : undefined;
176
+ if (url === undefined)
177
+ continue;
178
+ for (const { rule, level, says } of registryIssues(url)) {
179
+ hits.push({ rule, level, message: `Package ${name} ${says}.`, line: index + 1 });
180
+ }
181
+ }
182
+ return hits;
183
+ }
184
+ /** The package name of a yarn.lock entry header such as `"@scope/name@^1.0.0", "@scope/name@^1.1.0"`. */
185
+ function selectorName(header) {
186
+ const first = unquote(header.split(',')[0].trim());
187
+ const at = first.indexOf('@', 1);
188
+ return at > 0 ? first.slice(0, at) : first;
189
+ }
190
+ function pnpmLockHits(text) {
191
+ const hits = [];
192
+ let section = '';
193
+ let entry;
194
+ let block = false;
195
+ const flush = () => {
196
+ for (const { rule, level, says, line } of entry?.issues ?? []) {
197
+ hits.push({ rule, level, message: `Package ${entry.name} ${says}.`, line });
198
+ }
199
+ entry = undefined;
200
+ };
201
+ const check = (value, line) => {
202
+ const url = urlIn(unquote(value.trim()));
203
+ if (!entry || url === undefined)
204
+ return;
205
+ for (const issue of registryIssues(url)) {
206
+ if (!entry.issues.some(known => known.rule === issue.rule))
207
+ entry.issues.push({ ...issue, line });
208
+ }
209
+ };
210
+ for (const [index, line] of text.split(/\r?\n/).entries()) {
211
+ if (line.trim() === '' || line.trimStart().startsWith('#'))
212
+ continue;
213
+ if (!/^\s/.test(line)) {
214
+ flush();
215
+ section = line.slice(0, Math.max(0, line.indexOf(':')));
216
+ continue;
217
+ }
218
+ if (section !== 'packages')
219
+ continue;
220
+ const header = /^ {2}(\S.*?):\s*$/.exec(line);
221
+ if (header) {
222
+ flush();
223
+ entry = { name: pnpmName(unquote(header[1])), issues: [] };
224
+ block = false;
225
+ continue;
226
+ }
227
+ if (block) {
228
+ const nested = /^ {6,}[\w-]+:\s*(.+)$/.exec(line);
229
+ if (nested) {
230
+ check(nested[1], index + 1);
231
+ continue;
232
+ }
233
+ block = false;
234
+ }
235
+ const named = /^ {4}name:\s*(.+?)\s*$/.exec(line);
236
+ if (named && entry)
237
+ entry.name = unquote(named[1]);
238
+ const inline = /^ {4}resolution:\s*\{(.*)\}\s*$/.exec(line);
239
+ for (const pair of inline ? inline[1].split(/,\s*/) : [])
240
+ check(pair.slice(pair.indexOf(':') + 1), index + 1);
241
+ if (/^ {4}resolution:\s*$/.test(line))
242
+ block = true;
243
+ }
244
+ flush();
245
+ return hits;
246
+ }
247
+ /** The package name in a pnpm `packages` key: `/name/1.0.0` (v5), `/name@1.0.0` (v6) or `name@1.0.0(peer)` (v9). */
248
+ function pnpmName(key) {
249
+ const [first = '', second = ''] = key.replace(/^\//, '').split('/');
250
+ const bare = (segment) => segment.replace(/[@(].*$/, '');
251
+ return first.startsWith('@') ? `${first}/${bare(second)}` : bare(first);
252
+ }
253
+ function registryIssues(url) {
254
+ const protocol = /^([a-z][a-z0-9+.-]*):\/\//i.exec(url)?.[1]?.toLowerCase();
255
+ const where = host(url);
256
+ if (protocol === undefined || where === '' || protocol.endsWith('file'))
257
+ return [];
258
+ const issues = [];
259
+ if (insecureProtocols.has(protocol)) {
260
+ issues.push({ rule: 'lockfile-insecure-registry', level: 'high', says: `is downloaded over unencrypted ${protocol}:// from ${where}` });
261
+ }
262
+ if (!registryHosts.has(where)) {
263
+ issues.push({ rule: 'lockfile-foreign-host', level: 'medium', says: `resolves from ${where} instead of the npm registry` });
264
+ }
265
+ return issues;
266
+ }
267
+ function host(url) {
268
+ return /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/?#]*@)?(\[[^\]]*\]|[^/:?#]*)/i.exec(url)?.[1]?.toLowerCase() ?? '';
269
+ }
270
+ function urlIn(value) {
271
+ return /[a-z][a-z0-9+.-]*:\/\/\S+/i.exec(value)?.[0];
272
+ }
273
+ function unquote(value) {
274
+ return value.replace(/^["']|["']$/g, '');
275
+ }
276
+ /** A URL fit for a report: no credentials, no query string, bounded length. */
277
+ function display(url) {
278
+ return abbreviate(url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/?#]*@/i, '$1').replace(/\?[^#]*/, ''), 100);
279
+ }
280
+ function abbreviate(text, limit) {
281
+ return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
282
+ }
283
+ function pointer(path) {
284
+ return path.map(segment => JSON.stringify(segment)).join('');
285
+ }
286
+ /**
287
+ * Find the lines of the wanted values in JSON text that JSON.parse has already accepted. A member starts on the line
288
+ * of its key and ends on the line where its value ends. Only paths up to `depth` keys deep are tracked.
289
+ */
290
+ function locate(text, wanted, depth) {
291
+ const spans = new Map();
292
+ const stack = [];
293
+ let line = 1;
294
+ const child = () => {
295
+ const parent = stack.at(-1);
296
+ if (!parent)
297
+ return { path: '', line };
298
+ const path = parent.path === undefined || stack.length > depth ? undefined
299
+ : parent.path + (parent.array ? `#${parent.index}` : JSON.stringify(parent.key));
300
+ return { path, line: parent.array ? line : parent.keyLine };
301
+ };
302
+ const scalar = () => {
303
+ const { path, line: start } = child();
304
+ if (path !== undefined && wanted.has(path))
305
+ spans.set(path, { line: start, endLine: line });
306
+ };
307
+ for (let index = 0; index < text.length;) {
308
+ const char = text[index];
309
+ if (char === '\n')
310
+ line++;
311
+ if (char === '\n' || char === ' ' || char === '\t' || char === '\r' || char === ':') {
312
+ index++;
313
+ }
314
+ else if (char === ',') {
315
+ const parent = stack.at(-1);
316
+ if (parent?.array)
317
+ parent.index++;
318
+ else if (parent)
319
+ parent.expectKey = true;
320
+ index++;
321
+ }
322
+ else if (char === '"') {
323
+ const end = stringEnd(text, index);
324
+ const parent = stack.at(-1);
325
+ if (parent && !parent.array && parent.expectKey) {
326
+ const raw = text.slice(index + 1, end);
327
+ parent.key = raw.includes('\\') ? JSON.parse(text.slice(index, end + 1)) : raw;
328
+ parent.keyLine = line;
329
+ parent.expectKey = false;
330
+ }
331
+ else {
332
+ scalar();
333
+ }
334
+ index = end + 1;
335
+ }
336
+ else if (char === '{' || char === '[') {
337
+ const { path, line: start } = child();
338
+ stack.push({ path, line: start, array: char === '[', index: 0, key: '', keyLine: line, expectKey: char === '{' });
339
+ index++;
340
+ }
341
+ else if (char === '}' || char === ']') {
342
+ const frame = stack.pop();
343
+ if (frame?.path !== undefined && wanted.has(frame.path))
344
+ spans.set(frame.path, { line: frame.line, endLine: line });
345
+ index++;
346
+ }
347
+ else {
348
+ scalar();
349
+ while (index < text.length && !/[\s,\]}]/.test(text[index]))
350
+ index++;
351
+ }
352
+ }
353
+ return spans;
354
+ }
355
+ function stringEnd(text, start) {
356
+ for (let from = start + 1;;) {
357
+ const quote = text.indexOf('"', from);
358
+ if (quote < 0)
359
+ return text.length;
360
+ let slashes = 0;
361
+ while (text[quote - 1 - slashes] === '\\')
362
+ slashes++;
363
+ if (slashes % 2 === 0)
364
+ return quote;
365
+ from = quote + 1;
366
+ }
367
+ }
368
+ //# sourceMappingURL=npm-supply-chain.js.map
@@ -0,0 +1,12 @@
1
+ import type { Plugin, RuleDescriptor } from '../../core/engine/plugin.js';
2
+ import type { Finding } from '../../core/model/finding.js';
3
+ /** A line that contains this marker is never reported. */
4
+ export declare const ignoreMarker = "repometry-ignore-secret";
5
+ /** Files larger than this are not scanned. */
6
+ export declare const maxScannedBytes: number;
7
+ export declare function isPlaceholder(value: string): boolean;
8
+ export declare function shannonEntropy(value: string): number;
9
+ export declare const secretRules: readonly RuleDescriptor[];
10
+ /** Scans one file. Secret values never reach a finding: messages name only the kind of secret. */
11
+ export declare function scanSecrets(path: string, bytes: Uint8Array): Finding[];
12
+ export declare const secrets: Plugin;
@@ -0,0 +1,254 @@
1
+ import { isRecord, pluginApi } from '../../core/engine/plugin.js';
2
+ import { findingResult } from '../../core/model/finding.js';
3
+ import { sourceFile } from '../../core/model/snapshot.js';
4
+ /** A line that contains this marker is never reported. */
5
+ export const ignoreMarker = 'repometry-ignore-secret';
6
+ /** Files larger than this are not scanned. */
7
+ export const maxScannedBytes = 1024 * 1024;
8
+ /** A NUL byte within this prefix marks the file as binary. */
9
+ const binaryProbeBytes = 8 * 1024;
10
+ /** How much text after a private key header may hold its body and footer. */
11
+ const privateKeyLines = 400;
12
+ const privateKeyChars = 64 * 1024;
13
+ const skipped = `lines containing ${ignoreMarker} are skipped`;
14
+ const placeholder = new RegExp([
15
+ 'example', 'dummy', 'change[_-]?me', 'placeholder', 'sample', 'redacted', 'fake', 'your[_-]', 'x{3,}', '\\*{3,}', '\\.{3}',
16
+ '<[^>]*>', '\\$\\{', '\\{\\{', '%\\(', '^\\$[A-Za-z_]\\w*$', 'process\\.env', 'os\\.environ', '(.)\\1{5,}',
17
+ ].join('|'), 'i');
18
+ export function isPlaceholder(value) {
19
+ return placeholder.test(value);
20
+ }
21
+ export function shannonEntropy(value) {
22
+ const counts = new Map();
23
+ for (const char of value)
24
+ counts.set(char, (counts.get(char) ?? 0) + 1);
25
+ let entropy = 0;
26
+ for (const count of counts.values())
27
+ entropy -= (count / value.length) * Math.log2(count / value.length);
28
+ return entropy;
29
+ }
30
+ function body(match) {
31
+ return match.slice(1).find(group => group !== undefined) ?? match[0];
32
+ }
33
+ function random(value, minimumEntropy) {
34
+ return !isPlaceholder(value) && shannonEntropy(value) >= minimumEntropy;
35
+ }
36
+ function token(minimumEntropy) {
37
+ return match => random(body(match), minimumEntropy);
38
+ }
39
+ function awsSecret(match) {
40
+ const value = body(match);
41
+ return /[A-Z]/.test(value) && /[a-z]/.test(value) && random(value, 4);
42
+ }
43
+ const privateKeyFooter = /-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----/;
44
+ const keyBodyPlaceholder = /example|redacted|placeholder|dummy|x{6,}|\.{3}/i;
45
+ /** A real key has a footer and at least one line of base64 between header and footer, raw or inside a quoted string. */
46
+ function hasKeyBody(match, { lines, index }) {
47
+ let text = lines[index].slice((match.index ?? 0) + match[0].length);
48
+ for (let next = index + 1; next < Math.min(lines.length, index + privateKeyLines) && text.length < privateKeyChars; next++) {
49
+ text += '\n' + lines[next];
50
+ }
51
+ const footer = privateKeyFooter.exec(text);
52
+ if (footer === null)
53
+ return false;
54
+ const content = text.slice(0, footer.index);
55
+ return !keyBodyPlaceholder.test(content) && content.split(/\s+|\\[nr]/)
56
+ .some(part => /^[A-Za-z0-9+/]{40,}={0,2}$/.test(part.replace(/^['"`+,]+|['"`+,]+$/g, '')));
57
+ }
58
+ function isJwt(match) {
59
+ if (isPlaceholder(match[2]))
60
+ return false;
61
+ try {
62
+ const header = JSON.parse(Buffer.from(match[1], 'base64url').toString('utf8'));
63
+ return isRecord(header) && typeof header.alg === 'string';
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ const lineRules = [
70
+ { id: 'aws-access-key-id', level: 'high', message: 'Hard-coded AWS access key ID',
71
+ description: `Flags AWS access key IDs (AKIA or ASIA followed by 16 base32 characters); ${skipped}.`,
72
+ hint: /A[KS]IA/, pattern: /(?<![A-Za-z0-9])((?:AKIA|ASIA)[A-Z2-7]{16})(?![A-Za-z0-9])/g, accept: token(3) },
73
+ { id: 'aws-secret-access-key', level: 'high', message: 'Hard-coded AWS secret access key',
74
+ description: `Flags a 40-character base64 value assigned to an AWS secret access key name; ${skipped}.`, hint: /secret/i,
75
+ pattern: /(?:(?:aws[_.-]?)?secret[_.-]?access[_.-]?key|aws[_.-]?secret(?:[_.-]?key)?)["']?\s*(?::=|=>|[:=])\s*["']?([A-Za-z0-9/+]{40})(?![A-Za-z0-9/+=])/gi,
76
+ accept: awsSecret },
77
+ { id: 'github-token', level: 'high', message: 'Hard-coded GitHub token',
78
+ description: `Flags GitHub personal access, OAuth, user, server and refresh tokens (ghp_, gho_, ghu_, ghs_, ghr_, github_pat_); ${skipped}.`,
79
+ hint: /gh[pousr]_|github_pat_/, pattern: /(?<![A-Za-z0-9_])(?:gh[pousr]_([A-Za-z0-9]{36})|github_pat_(\w{82}))(?![A-Za-z0-9_])/g,
80
+ accept: token(3.5) },
81
+ { id: 'gitlab-token', level: 'high', message: 'Hard-coded GitLab personal access token',
82
+ description: `Flags GitLab personal access tokens (glpat- followed by at least 20 characters); ${skipped}.`,
83
+ hint: /glpat-/, pattern: /(?<![\w-])glpat-([\w-]{20,})(?![\w-])/g, accept: token(3) },
84
+ { id: 'slack-token', level: 'high', message: 'Hard-coded Slack token',
85
+ description: `Flags Slack bot, user, app, refresh and legacy tokens (xoxb-, xoxp-, xoxa-, xoxr-, xoxs-); ${skipped}.`,
86
+ hint: /xox[baprs]-/, pattern: /(?<![\w-])xox[baprs]-(\d{1,13}-[0-9A-Za-z-]{8,})/g, accept: token(3) },
87
+ { id: 'slack-webhook', level: 'high', message: 'Hard-coded Slack webhook URL',
88
+ description: `Flags Slack incoming webhook, workflow and trigger URLs on hooks.slack.com; ${skipped}.`, hint: /hooks\.slack\.com/,
89
+ pattern: /(?:https?:\/\/)?hooks\.slack\.com\/(?:services|workflows|triggers)\/([A-Za-z0-9+/]{43,56})/g, accept: token(3.5) },
90
+ { id: 'stripe-secret-key', level: 'high', message: 'Hard-coded Stripe live secret key',
91
+ description: `Flags Stripe live secret and restricted keys (sk_live_, rk_live_); test and publishable keys are ignored; ${skipped}.`,
92
+ hint: /k_live_/, pattern: /(?<![\w])[rs]k_live_([0-9A-Za-z]{24,247})(?![0-9A-Za-z])/g, accept: token(3.5) },
93
+ { id: 'google-api-key', level: 'medium', message: 'Hard-coded Google API key',
94
+ description: `Flags Google API keys (AIza followed by 35 characters), often meant for clients but still worth restricting; ${skipped}.`,
95
+ hint: /AIza/, pattern: /(?<![\w-])AIza([0-9A-Za-z_-]{35})(?![\w-])/g, accept: token(3.5) },
96
+ { id: 'npm-token', level: 'high', message: 'Hard-coded npm access token',
97
+ description: `Flags npm access tokens (npm_ followed by 36 characters); ${skipped}.`,
98
+ hint: /npm_/, pattern: /(?<![\w])npm_([A-Za-z0-9]{36})(?![\w])/g, accept: token(3.5) },
99
+ { id: 'private-key', level: 'high', message: 'Hard-coded private key',
100
+ description: `Flags PEM, OpenSSH and PGP private key blocks that have a base64 body and a footer; ${skipped}.`,
101
+ hint: /-----BEGIN/, pattern: /-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----/g, accept: hasKeyBody },
102
+ { id: 'jwt', level: 'medium', message: 'Hard-coded JSON Web Token',
103
+ description: `Flags JSON Web Tokens whose first segment decodes to a JSON header with an alg field; ${skipped}.`,
104
+ hint: /eyJ/, pattern: /(?<![\w-])(eyJ[A-Za-z0-9_-]{8,})\.eyJ[A-Za-z0-9_-]{8,}\.([A-Za-z0-9_-]{16,})/g, accept: isJwt },
105
+ ];
106
+ /** Name, optional type annotation, assignment operator and a quoted literal without whitespace. */
107
+ const assignment = /(?<![\w$-])(["'`]?)([A-Za-z_$][\w$-]*)\1(?:\s*:\s*[A-Za-z_$][\w$.<>]*)?\s*(?::=|=>|[:=])\s*(["'`])([^\s"'`\\]{16,})\3/g;
108
+ const keyQualifiers = new Set(['secret', 'access', 'private', 'auth', 'signing', 'encryption', 'master']);
109
+ function credentialKind(name) {
110
+ const words = name.replace(/([a-z\d])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
111
+ .toLowerCase().split(/[^a-z\d]+/).filter(Boolean);
112
+ const last = words.at(-1);
113
+ const previous = words.at(-2);
114
+ if (last === 'password' || last === 'passwd' || last === 'pwd' || last === 'passphrase')
115
+ return 'password';
116
+ if (last === 'secret' || last === 'token')
117
+ return last;
118
+ if (last === 'apikey' || (last === 'key' && previous === 'api'))
119
+ return 'API key';
120
+ if (last === 'key' && previous !== undefined && keyQualifiers.has(previous))
121
+ return 'secret key';
122
+ return undefined;
123
+ }
124
+ /** Paths, URLs and dotted, dashed or underscored words are names, not secrets. */
125
+ function looksLikeName(value) {
126
+ const parts = value.split(/[._-]/);
127
+ return /^(?:\.{0,2}\/|~\/|[a-z][\w+.-]*:\/\/)/i.test(value) || (parts.length > 1 && parts.every(part => /^[A-Za-z]*\d*$/.test(part)));
128
+ }
129
+ /** A letter and a non-letter rule out plain and camel-cased words; hex has a smaller alphabet, so a lower entropy bar. */
130
+ function looksSecret(value) {
131
+ return /[A-Za-z]/.test(value) && /[^A-Za-z]/.test(value) && !looksLikeName(value)
132
+ && random(value, /^[\dA-Fa-f-]+$/.test(value) ? 3 : 3.5);
133
+ }
134
+ function assignedSecret(line, claimed) {
135
+ for (const match of line.matchAll(assignment)) {
136
+ const value = match[4];
137
+ const end = (match.index ?? 0) + match[0].length - 1;
138
+ if (claimed.some(([from, to]) => end - value.length < to && from < end))
139
+ continue;
140
+ const kind = credentialKind(match[2]);
141
+ if (kind !== undefined && looksSecret(value))
142
+ return kind;
143
+ }
144
+ return undefined;
145
+ }
146
+ const genericRule = { id: 'generic-secret-assignment', category: 'secret',
147
+ description: 'Flags a quoted high-entropy literal of 16 or more characters assigned to a password, secret, token or API key name, '
148
+ + `ignoring placeholders such as example, dummy, changeme, xxx, \${...} and process.env; ${skipped}.` };
149
+ const sensitiveRule = { id: 'sensitive-file', category: 'secret',
150
+ description: 'Flags files that usually hold credentials: .env and .env.* except .env.example, .env.sample and .env.template, '
151
+ + '*.pem and *.key unless they hold only public certificates or keys, *.p12, *.pfx, id_rsa, id_dsa, id_ecdsa, id_ed25519, '
152
+ + `.git-credentials, and .npmrc or .pypirc with a literal auth token; ${ignoreMarker} on the first line skips the file.` };
153
+ export const secretRules = [
154
+ ...lineRules.map(({ id, description }) => ({ id, category: 'secret', description })), genericRule, sensitiveRule,
155
+ ];
156
+ const sshKeys = new Set(['id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519']);
157
+ const envTemplates = new Set(['example', 'sample', 'template']);
158
+ const publicPem = /^(?:(?:TRUSTED |X509 )?CERTIFICATE|(?:NEW )?CERTIFICATE REQUEST|X509 CRL|(?:RSA |SSH2 )?PUBLIC KEY|PKCS7|CMS|(?:DH|EC) PARAMETERS)$/;
159
+ const npmAuth = /(?:^|:)_(?:authToken|auth|password)\s*=\s*["']?([^\s"']+)/;
160
+ const pypiPassword = /^\s*password\s*[:=]\s*(\S+)/i;
161
+ function extension(name) {
162
+ const dot = name.lastIndexOf('.');
163
+ return dot > 0 ? name.slice(dot).toLowerCase() : '';
164
+ }
165
+ function onlyPublicPem(lines) {
166
+ const labels = lines.flatMap(line => [...line.matchAll(/-----BEGIN ([A-Z0-9 ]+)-----/g)].map(match => match[1]));
167
+ return labels.length > 0 && labels.every(label => publicPem.test(label));
168
+ }
169
+ function hasLiteral(lines, pattern) {
170
+ return lines.some(line => {
171
+ if (line.includes(ignoreMarker) || /^\s*[#;]/.test(line))
172
+ return false;
173
+ const value = pattern.exec(line)?.[1];
174
+ return value !== undefined && !isPlaceholder(value);
175
+ });
176
+ }
177
+ function keystoreKind(name) {
178
+ return extension(name) === '.p12' || extension(name) === '.pfx' ? 'PKCS#12 keystore' : undefined;
179
+ }
180
+ function sensitiveTextKind(name, lines) {
181
+ if (name === '.env' || (name.startsWith('.env.') && !envTemplates.has(name.slice(5).toLowerCase())))
182
+ return 'environment file';
183
+ if ((extension(name) === '.pem' || extension(name) === '.key') && !onlyPublicPem(lines))
184
+ return 'key file';
185
+ if (sshKeys.has(name))
186
+ return 'SSH private key file';
187
+ if (name === '.git-credentials')
188
+ return 'Git credential store';
189
+ if (name === '.npmrc' && hasLiteral(lines, npmAuth))
190
+ return 'npm configuration with an auth token';
191
+ if (name === '.pypirc' && hasLiteral(lines, pypiPassword))
192
+ return 'PyPI configuration with a password';
193
+ return undefined;
194
+ }
195
+ function finding(rule, level, message, path, line) {
196
+ return { tool: 'secrets', rule, category: 'secret', level, message, path, line, endLine: line };
197
+ }
198
+ function lineFindings(path, context) {
199
+ const line = context.lines[context.index];
200
+ const claimed = [];
201
+ const findings = [];
202
+ for (const rule of lineRules) {
203
+ if (!rule.hint.test(line))
204
+ continue;
205
+ for (const match of line.matchAll(rule.pattern)) {
206
+ if (!rule.accept(match, context))
207
+ continue;
208
+ claimed.push([match.index ?? 0, (match.index ?? 0) + match[0].length]);
209
+ if (!findings.some(item => item.rule === rule.id))
210
+ findings.push(finding(rule.id, rule.level, rule.message, path, context.index + 1));
211
+ }
212
+ }
213
+ const kind = /pass|pwd|secret|token|key/i.test(line) ? assignedSecret(line, claimed) : undefined;
214
+ if (kind !== undefined)
215
+ findings.push(finding(genericRule.id, 'medium', `Likely hard-coded ${kind}`, path, context.index + 1));
216
+ return findings;
217
+ }
218
+ /** Scans one file. Secret values never reach a finding: messages name only the kind of secret. */
219
+ export function scanSecrets(path, bytes) {
220
+ if (bytes.length > maxScannedBytes)
221
+ return [];
222
+ const name = path.slice(path.lastIndexOf('/') + 1);
223
+ const file = (kind) => finding(sensitiveRule.id, 'medium', `Sensitive file: ${kind}`, path, 1);
224
+ if (bytes.subarray(0, binaryProbeBytes).includes(0)) {
225
+ const kind = keystoreKind(name);
226
+ return kind === undefined ? [] : [file(kind)];
227
+ }
228
+ const lines = new TextDecoder().decode(bytes).split(/\r\n|\r|\n/);
229
+ const findings = [];
230
+ const kind = keystoreKind(name) ?? sensitiveTextKind(name, lines);
231
+ if (kind !== undefined && !lines[0].includes(ignoreMarker))
232
+ findings.push(file(kind));
233
+ for (let index = 0; index < lines.length; index++) {
234
+ if (!lines[index].includes(ignoreMarker))
235
+ findings.push(...lineFindings(path, { lines, index }));
236
+ }
237
+ return findings;
238
+ }
239
+ export const secrets = {
240
+ id: 'secrets', version: '1.0.0', api: pluginApi,
241
+ kinds: ['security'],
242
+ // `**/*` skips dotfiles, so `**/.*` adds .env, .npmrc and files under dot directories.
243
+ claims: { globs: ['**/*', '**/.*'], scanOnly: true },
244
+ produces: [{ contract: findingResult.id, persistence: 'report' }],
245
+ rules: secretRules,
246
+ operations: [{
247
+ id: 'scan', role: 'inspection', inputs: { source: sourceFile }, output: findingResult,
248
+ execute(inputs) {
249
+ const { path, bytes } = inputs.read('source', sourceFile);
250
+ return { measurements: [], findings: scanSecrets(path, bytes) };
251
+ },
252
+ }],
253
+ };
254
+ //# sourceMappingURL=secrets.js.map
@@ -51,6 +51,13 @@ export declare const securityCategories: readonly ['security', 'dependency', 'se
51
51
  export declare function renderFileView(container: HTMLElement, view: View, details: InspectionDetails, navigation: Navigation): void;
52
52
  /** The folders all of whose files are only counted, found in one pass over the files. */
53
53
  export declare function unreadFolders(files: readonly Pick<Metrics, 'path' | 'analysed'>[]): Set<string>;
54
+ /**
55
+ * The entries a page shows, 1-based, counting rows and not the fold of ignored files, which takes a place in the list
56
+ * but is no entry of its own. None where the page holds only the fold.
57
+ */
58
+ export declare function entryRange(display: readonly {
59
+ readonly kind: string;
60
+ }[], first: number, shown: number): [number, number] | null;
54
61
  type MapShape = 'rings' | 'tiles';
55
62
  interface SunburstOptions {
56
63
  readonly metric: HotspotMetric;