repometry 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +3 -0
  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 +5 -0
  40. package/target/main/ts/report/html/app/viewer-source.js +33 -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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repometry",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Track repository metrics without SaaS",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -154,7 +154,8 @@
154
154
  "properties": {
155
155
  "covered": { "$ref": "#/$defs/lcovLineRanges" },
156
156
  "uncovered": { "$ref": "#/$defs/lcovLineRanges" },
157
- "partial": { "$ref": "#/$defs/lcovLineRanges" }
157
+ "partial": { "$ref": "#/$defs/lcovLineRanges" },
158
+ "hits": { "$ref": "#/$defs/lcovHitRuns" }
158
159
  }
159
160
  }
160
161
  },
@@ -168,6 +169,16 @@
168
169
  "items": false
169
170
  }
170
171
  },
172
+ "lcovHitRuns": {
173
+ "type": "array",
174
+ "description": "Ordered inclusive ranges of measured lines with the same hit count.",
175
+ "items": {
176
+ "type": "array",
177
+ "minItems": 3,
178
+ "prefixItems": [{ "type": "integer", "minimum": 1 }, { "type": "integer", "minimum": 1 }, { "type": "integer", "minimum": 0 }],
179
+ "items": false
180
+ }
181
+ },
171
182
  "pluginRule": {
172
183
  "type": "object",
173
184
  "required": ["id", "category"],
@@ -503,6 +503,9 @@ code.fx-function-name { font-size: .75rem; color: var(--secondary); }
503
503
  .src-excerpt .src-line { grid-template-columns: .375rem 2.75rem max-content; }
504
504
  .src-excerpt .src-line:hover { background: transparent; }
505
505
  .src-range, .src-excerpt .src-range:hover { background: var(--warn-bg); box-shadow: inset 3px 0 0 var(--grade-c); }
506
+ /* A finding's excerpt follows its severity badge: amber for medium (above), red for high, grey for low and unknown. */
507
+ .fx-occurrences[data-level="high"] .src-range { background: var(--bad-bg); box-shadow: inset 3px 0 0 var(--bad); }
508
+ .fx-occurrences:is([data-level="low"], [data-level="unknown"]) .src-range { background: var(--selected); box-shadow: inset 3px 0 0 var(--neutral-2); }
506
509
  .src-more { display: block; padding: .1875rem 1rem .125rem 3.125rem; font-family: var(--sans); font-size: .75rem; }
507
510
 
508
511
  /* Map heading with its shape switch; the treemap's labels and folder frames. */
@@ -17,5 +17,5 @@ interface GitFile {
17
17
  }
18
18
  export declare function gitTreeFiles(directory: string, commit: string, prefix?: string, includeSize?: boolean): Promise<readonly GitFile[]>;
19
19
  export declare function gitBlobText(directory: string, oid: string): Promise<string>;
20
- export declare function readGitCommit(directory: string, revision: string, excludes: (path: string) => boolean): Promise<SourceSnapshot>;
20
+ export declare function readGitCommit(directory: string, revision: string, excludes: (path: string) => boolean, claims?: (path: string) => boolean): Promise<SourceSnapshot>;
21
21
  export {};
@@ -2,6 +2,7 @@ import { realpath } from 'node:fs/promises';
2
2
  import { execFile, spawnSync } from 'node:child_process';
3
3
  import { promisify } from 'node:util';
4
4
  import { comparePaths, isExcludedDirectory, isSourcePath, textLineCount, utf8 } from '../../core/model/snapshot.js';
5
+ import { isClaimedText, maxClaimedFileBytes } from '../../core/model/source.js';
5
6
  import { isGeneratedSource } from '../../core/profile/exclusions.js';
6
7
  const git = promisify(execFile);
7
8
  const maxBuffer = 64 * 1024 * 1024;
@@ -82,7 +83,7 @@ export async function gitBlobText(directory, oid) {
82
83
  const result = await git('git', ['--no-replace-objects', 'cat-file', 'blob', oid], { cwd: directory, env, encoding: 'buffer', maxBuffer });
83
84
  return utf8(result.stdout);
84
85
  }
85
- export async function readGitCommit(directory, revision, excludes) {
86
+ export async function readGitCommit(directory, revision, excludes, claims) {
86
87
  const id = await resolveGitCommit(directory, revision);
87
88
  const tracked = (await gitTreeFiles(directory, id, undefined, true)).filter(({ path }) => !path.split('/').slice(0, -1).some(isExcludedDirectory) && !excludes(path));
88
89
  const entries = tracked.filter(entry => isSourcePath(entry.path));
@@ -97,13 +98,26 @@ export async function readGitCommit(directory, revision, excludes) {
97
98
  generated.add(path);
98
99
  return [];
99
100
  });
101
+ const claimed = tracked.filter(({ path }) => !isSourcePath(path) && claims?.(path));
102
+ const oversized = new Set(claimed.filter(({ size }) => size !== undefined && size > maxClaimedFileBytes).map(({ path }) => path));
103
+ const requested = new Set(claimed.filter(({ path }) => !oversized.has(path)).map(({ oid }) => oid));
104
+ const claimedBlobs = new Map();
105
+ const counts = inventoryLineCounts(directory, tracked.filter(({ path }) => !oversized.has(path)), blobs, (oid, bytes) => { if (requested.has(oid) && isClaimedText(bytes))
106
+ claimedBlobs.set(oid, bytes); });
107
+ for (const { path, oid } of claimed) {
108
+ const bytes = claimedBlobs.get(oid);
109
+ if (bytes && !oversized.has(path))
110
+ files.push({ path, bytes });
111
+ }
100
112
  files.sort((left, right) => comparePaths(left.path, right.path));
101
- const counts = inventoryLineCounts(directory, tracked, blobs);
102
113
  const inventory = tracked.filter(({ path }) => !generated.has(path)).map(({ path, oid, size }) => ({ path, lines: counts.get(oid) ?? null, ...(size === undefined ? {} : { bytes: size }) }));
103
- return { subject: { kind: 'commit', id }, files, inventory, generatedExcluded: [...generated].sort(comparePaths) };
114
+ return { subject: { kind: 'commit', id }, files, inventory, generatedExcluded: [...generated].sort(comparePaths),
115
+ ...(oversized.size ? { oversizedClaims: [...oversized].sort(comparePaths) } : {}) };
104
116
  }
105
- function inventoryLineCounts(directory, entries, sources) {
117
+ function inventoryLineCounts(directory, entries, sources, capture) {
106
118
  const lines = new Map([...sources].map(([oid, value]) => [oid, textLineCount(value)]));
119
+ for (const [oid, bytes] of sources)
120
+ capture(oid, bytes);
107
121
  const entriesById = new Map(entries.map(entry => [entry.oid, entry]));
108
122
  let batch = [];
109
123
  let bytes = 0;
@@ -119,8 +133,10 @@ function inventoryLineCounts(directory, entries, sources) {
119
133
  flush();
120
134
  return lines;
121
135
  function flush() {
122
- for (const [oid, value] of readBlobs(directory, batch))
136
+ for (const [oid, value] of readBlobs(directory, batch)) {
123
137
  lines.set(oid, textLineCount(value));
138
+ capture(oid, value);
139
+ }
124
140
  batch = [];
125
141
  bytes = 0;
126
142
  }
@@ -7,7 +7,7 @@ export interface SourceSelection {
7
7
  readonly revision: string;
8
8
  };
9
9
  }
10
- export declare function readInspectionSource(request: SourceSelection, excludes: (path: string) => boolean): Promise<{
10
+ export declare function readInspectionSource(request: SourceSelection, excludes: (path: string) => boolean, claims?: (path: string) => boolean): Promise<{
11
11
  root: string;
12
12
  snapshot: import("../../plugin.js").SourceSnapshot;
13
13
  excludedOutput: string | null;
@@ -1,20 +1,26 @@
1
1
  import { realpath } from 'node:fs/promises';
2
2
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
3
- import { gitRoot, readGitCommit } from './git.js';
3
+ import { gitRoot, gitUtf8, readGitCommit } from './git.js';
4
4
  import { containsPath, readWorkingTree } from './local.js';
5
- export async function readInspectionSource(request, excludes) {
5
+ export async function readInspectionSource(request, excludes, claims) {
6
6
  const root = await realpath('workingTree' in request.source ? request.directory : await gitRoot(request.directory));
7
7
  const output = await physicalPath(resolve(request.output));
8
8
  if (containsPath(output, root) || output.split(sep).includes('.git')) {
9
9
  throw new Error('Choose a dedicated report directory outside Git metadata');
10
10
  }
11
11
  const snapshot = 'workingTree' in request.source
12
- ? await readWorkingTree(root, output, excludes)
13
- : await readGitCommit(root, request.source.revision, excludes);
12
+ ? await readWorkingTree(root, output, excludes, await trackedClaims(root, claims))
13
+ : await readGitCommit(root, request.source.revision, excludes, claims);
14
14
  const excludedOutput = snapshot.subject.kind === 'working-tree' && containsPath(root, output)
15
15
  ? relative(root, output).split(sep).join('/') : null;
16
16
  return { root, snapshot, excludedOutput, output };
17
17
  }
18
+ async function trackedClaims(directory, claims) {
19
+ if (!claims || !await gitRoot(directory).catch(() => undefined))
20
+ return claims;
21
+ const tracked = new Set((await gitUtf8(directory, ['ls-files', '--cached', '-z', '--', '.'])).split('\0'));
22
+ return (path) => tracked.has(path) && claims(path);
23
+ }
18
24
  async function physicalPath(path) {
19
25
  try {
20
26
  return await realpath(path);
@@ -1,3 +1,3 @@
1
1
  import type { SourceSnapshot } from '../../core/model/snapshot.js';
2
2
  export declare function containsPath(parent: string, path: string): boolean;
3
- export declare function readWorkingTree(directory: string, output: string, excludes: (path: string) => boolean): Promise<SourceSnapshot>;
3
+ export declare function readWorkingTree(directory: string, output: string, excludes: (path: string) => boolean, claims?: (path: string) => boolean): Promise<SourceSnapshot>;
@@ -1,15 +1,17 @@
1
- import { readdir, realpath, readFile } from 'node:fs/promises';
1
+ import { lstat, readdir, realpath, readFile } from 'node:fs/promises';
2
2
  import { isAbsolute, join, relative, sep } from 'node:path';
3
3
  import { comparePaths, isExcludedDirectory, isSourcePath, workingSnapshot } from '../../core/model/snapshot.js';
4
+ import { isClaimedText, maxClaimedFileBytes } from '../../core/model/source.js';
4
5
  import { isGeneratedSource } from '../../core/profile/exclusions.js';
5
6
  export function containsPath(parent, path) {
6
7
  const rest = relative(parent, path);
7
8
  return rest === '' || (!isAbsolute(rest) && rest !== '..' && !rest.startsWith(`..${sep}`));
8
9
  }
9
- export async function readWorkingTree(directory, output, excludes) {
10
+ export async function readWorkingTree(directory, output, excludes, claims) {
10
11
  const root = await realpath(directory);
11
12
  const files = [];
12
13
  const generatedExcluded = [];
14
+ const oversizedClaims = [];
13
15
  if (containsPath(output, root))
14
16
  throw new Error('The output directory must be separate from the source root');
15
17
  async function visit(folder, prefix) {
@@ -21,16 +23,33 @@ export async function readWorkingTree(directory, output, excludes) {
21
23
  if (entry.isDirectory() && !isExcludedDirectory(entry.name) && absolute !== output) {
22
24
  await visit(absolute, `${path}/`);
23
25
  }
24
- else if (entry.isFile() && isSourcePath(path)) {
25
- const bytes = await readFile(absolute);
26
- if (isGeneratedSource(bytes))
27
- generatedExcluded.push(path);
28
- else
29
- files.push({ path, bytes });
30
- }
26
+ else if (entry.isFile())
27
+ await read(path, absolute);
28
+ }
29
+ }
30
+ async function read(path, absolute) {
31
+ if (isSourcePath(path)) {
32
+ const bytes = await readFile(absolute);
33
+ if (isGeneratedSource(bytes))
34
+ generatedExcluded.push(path);
35
+ else
36
+ files.push({ path, bytes });
37
+ return;
38
+ }
39
+ if (!claims?.(path))
40
+ return;
41
+ if ((await lstat(absolute)).size > maxClaimedFileBytes) {
42
+ oversizedClaims.push(path);
43
+ return;
31
44
  }
45
+ const bytes = await readFile(absolute);
46
+ if (bytes.length > maxClaimedFileBytes)
47
+ oversizedClaims.push(path);
48
+ else if (isClaimedText(bytes))
49
+ files.push({ path, bytes });
32
50
  }
33
51
  await visit(root, '');
34
- return { ...workingSnapshot(files), generatedExcluded: generatedExcluded.sort(comparePaths) };
52
+ return { ...workingSnapshot(files), generatedExcluded: generatedExcluded.sort(comparePaths),
53
+ ...(oversizedClaims.length ? { oversizedClaims: oversizedClaims.sort(comparePaths) } : {}) };
35
54
  }
36
55
  //# sourceMappingURL=local.js.map
@@ -1,9 +1,11 @@
1
1
  import { isRecord } from '../../core/engine/plugin.js';
2
2
  import { validSubjectId } from '../../report/json/validation/report.js';
3
- import { exclusionMatcher, normalizeExclusions } from '../../core/profile/exclusions.js';
4
- import { comparePaths, isSourcePath, workingSnapshot } from '../../core/model/snapshot.js';
3
+ import { exclusionMatcher, normalizeExclusions, sourceExclusionMatcher } from '../../core/profile/exclusions.js';
4
+ import { comparePaths, isExcludedDirectory, isSourcePath, workingSnapshot } from '../../core/model/snapshot.js';
5
+ import { isClaimedText } from '../../core/model/source.js';
5
6
  const schemaV1 = 'urn:repometry:schema:worker-input:1';
6
7
  const schemaV2 = 'urn:repometry:schema:worker-input:2';
8
+ const schemaV3 = 'urn:repometry:schema:worker-input:3';
7
9
  export const workerRoute = '/v1/inspect';
8
10
  export const maxWorkerInput = 16 * 1024 * 1024;
9
11
  export const maxWorkerResult = 64 * 1024 * 1024;
@@ -13,20 +15,23 @@ export function workerToken(value = process.env.REPOMETRY_WORKER_TOKEN) {
13
15
  return value;
14
16
  }
15
17
  export function encodeWorkerInput(input) {
16
- const { subject, files, inventory, generatedExcluded } = input.snapshot;
18
+ const { subject, files, inventory, generatedExcluded, oversizedClaims } = input.snapshot;
17
19
  const excludedPaths = input.excludedPaths ?? [];
18
- const profile = excludedPaths.length === 0 ? { schema: schemaV1 } : { schema: schemaV2, excludedPaths };
20
+ const hasClaims = oversizedClaims?.length || files.some(file => !isSourcePath(file.path));
21
+ const profile = hasClaims ? { schema: schemaV3, excludedPaths, oversizedClaims: oversizedClaims ?? [] }
22
+ : excludedPaths.length === 0 ? { schema: schemaV1 } : { schema: schemaV2, excludedPaths };
19
23
  return JSON.stringify({ ...profile, subject, excludedOutput: input.excludedOutput, coverage: input.coverage ?? null,
20
24
  files: files.map(({ path, bytes }) => ({ path, base64: Buffer.from(bytes).toString('base64') })),
21
25
  ...(inventory === undefined ? {} : { inventory }), ...(generatedExcluded?.length ? { generatedExcluded } : {}) });
22
26
  }
23
27
  export function decodeWorkerInput(value) {
24
- if (!isRecord(value) || (value.schema !== schemaV1 && value.schema !== schemaV2) || !isSubject(value.subject) || !Array.isArray(value.files)) {
28
+ if (!isRecord(value) || (value.schema !== schemaV1 && value.schema !== schemaV2 && value.schema !== schemaV3)
29
+ || !isSubject(value.subject) || !Array.isArray(value.files)) {
25
30
  throw new Error('Invalid worker input envelope');
26
31
  }
27
32
  const { subject, excludedOutput } = value;
28
- const excludedPaths = value.schema === schemaV2 ? normalizeExclusions(value.excludedPaths) : [];
29
- const excludes = exclusionMatcher(excludedPaths);
33
+ const excludedPaths = value.schema === schemaV1 ? [] : normalizeExclusions(value.excludedPaths);
34
+ const excludes = value.schema === schemaV3 ? sourceExclusionMatcher(excludedPaths) : exclusionMatcher(excludedPaths);
30
35
  if (excludedOutput !== null && (typeof excludedOutput !== 'string' || !safePath(excludedOutput)))
31
36
  throw new Error('Invalid excluded output');
32
37
  if (subject.kind === 'commit' && excludedOutput !== null)
@@ -34,7 +39,7 @@ export function decodeWorkerInput(value) {
34
39
  const files = [];
35
40
  const paths = new Set();
36
41
  for (const item of value.files) {
37
- if (!isRecord(item) || typeof item.path !== 'string' || !safePath(item.path) || !isSourcePath(item.path) || excludes(item.path)
42
+ if (!isRecord(item) || typeof item.path !== 'string' || !safePath(item.path) || excludes(item.path)
38
43
  || typeof item.base64 !== 'string') {
39
44
  throw new Error('Invalid worker source file');
40
45
  }
@@ -43,6 +48,9 @@ export function decodeWorkerInput(value) {
43
48
  const bytes = Buffer.from(item.base64, 'base64');
44
49
  if (bytes.toString('base64') !== item.base64)
45
50
  throw new Error('Invalid worker source encoding');
51
+ if (!isSourcePath(item.path) && (value.schema !== schemaV3 || !isClaimedText(bytes) || excludedParent(item.path))) {
52
+ throw new Error('Invalid worker claimed file');
53
+ }
46
54
  paths.add(item.path);
47
55
  files.push({ path: item.path, bytes });
48
56
  }
@@ -52,9 +60,26 @@ export function decodeWorkerInput(value) {
52
60
  files.sort((a, b) => comparePaths(a.path, b.path));
53
61
  const inventory = readInventory(value.inventory, excludes);
54
62
  const generatedExcluded = readGeneratedExclusions(value.generatedExcluded, paths, inventory);
55
- return { snapshot: { subject, files, ...(inventory === undefined ? {} : { inventory }), generatedExcluded },
63
+ const oversizedClaims = value.schema === schemaV3 ? readOversizedClaims(value.oversizedClaims, paths, excludes) : [];
64
+ return { snapshot: { subject, files, ...(inventory === undefined ? {} : { inventory }), generatedExcluded,
65
+ ...(oversizedClaims.length ? { oversizedClaims } : {}) },
56
66
  excludedOutput, excludedPaths, coverage: readCoverage(value.coverage) };
57
67
  }
68
+ function readOversizedClaims(value, paths, excludes) {
69
+ if (!Array.isArray(value))
70
+ throw new Error('Invalid worker oversized claims');
71
+ const claimed = new Set();
72
+ for (const path of value) {
73
+ if (typeof path !== 'string' || !safePath(path) || excludedParent(path) || excludes(path) || paths.has(path)) {
74
+ throw new Error('Invalid worker oversized claim');
75
+ }
76
+ claimed.add(path);
77
+ }
78
+ return [...claimed].sort(comparePaths);
79
+ }
80
+ function excludedParent(path) {
81
+ return path.split('/').slice(0, -1).some(isExcludedDirectory);
82
+ }
58
83
  function readGeneratedExclusions(value, sourcePaths, inventory) {
59
84
  if (value === undefined)
60
85
  return [];
@@ -1,4 +1,5 @@
1
1
  import type { Plugin } from '../core/engine/plugin.js';
2
2
  import type { Report } from '../core/model/report.js';
3
3
  import type { AnalysisInput } from '../core/usecases/inspect.js';
4
+ export declare function claimsNativeFile(path: string): boolean;
4
5
  export declare function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths, coverage: inputCoverage }: AnalysisInput, additional?: readonly Plugin[]): Promise<Report>;
@@ -5,7 +5,8 @@ import { ReportProducts } from '../core/engine/report-products.js';
5
5
  import { definitions } from '../core/model/measurement.js';
6
6
  import { debtModel } from '../core/model/quality-summary.js';
7
7
  import { reportSchema } from '../core/model/report.js';
8
- import { comparePaths, digest, sourceDirectoriesExcluded, sourceExtensions, sourceFile, sourceLineCounts, textLineCount } from '../core/model/snapshot.js';
8
+ import { comparePaths, digest, isSourcePath, sourceDirectoriesExcluded, sourceExtensions, sourceFile, sourceLineCounts, textLineCount } from '../core/model/snapshot.js';
9
+ import { isClaimedText, maxClaimedFileBytes } from '../core/model/source.js';
9
10
  import { defaultSourceExclusions, exclusionMatcher, generatedSourcePolicy, sourceExclusionMatcher } from '../core/profile/exclusions.js';
10
11
  import { duplicationSettings, structuralRules } from '../core/profile/maintainability.js';
11
12
  import { coverage, coverageResult, lcovInput } from '../plugins/coverage/coverage.js';
@@ -13,17 +14,22 @@ import { duplication, duplicationInput } from '../plugins/duplication/duplicatio
13
14
  import { babelProvider, babelTypes, parserDefaults } from '../plugins/language-js/babel-provider.js';
14
15
  import { fileQuality, maintainability } from '../plugins/maintainability/maintainability.js';
15
16
  import { structure } from '../plugins/structure/structure.js';
17
+ import { securityPlugins } from './security-plugins.js';
16
18
  const sourcePlugins = [babelProvider, { ...structure, tools: babelTypes }, { ...maintainability, tools: babelTypes }];
17
19
  const selected = ['structure/size', 'structure/complexity', 'maintainability/file'];
18
20
  const bindings = new Map(selected.map(operation => [operation, { syntax: { operation: 'babel-syntax/parse' } }]));
19
21
  const sourcePlan = plan({ plugins: sourcePlugins, select: selected, inputs: new Map([['file', sourceFile.id]]), bindings });
20
22
  const duplicationPlan = plan({ plugins: [duplication], select: ['duplication/detect'], inputs: new Map([['sources', duplicationInput.id]]) });
21
23
  const coveragePlan = plan({ plugins: [coverage], select: ['lcov/import', 'lcov/lines'], inputs: new Map([['lcov', lcovInput.id]]) });
24
+ const securityClaims = securityPlugins.map(plugin => claimMatcher(plugin.claims));
25
+ export function claimsNativeFile(path) {
26
+ return securityClaims.some(match => match(path));
27
+ }
22
28
  const measurementDefinitions = {
23
29
  [definitions.lines]: 'Physical lines including blank lines and comments. A final line terminator does not add a line.',
24
30
  [definitions.functions]: 'Babel function nodes with bodies, including nested functions and methods.',
25
31
  [definitions.complexity]: 'One plus branches in the function body: if, ternary, loops, catch, non-default switch cases and logical operators. Nested functions are measured separately. Line and column are 1-based and columns count UTF-16 units.',
26
- [definitions.coverage]: 'Distinct covered DA lines divided by the distinct DA lines listed for mapped files. Duplicate records are merged by the presence of any hit. A zero denominator has no ratio.',
32
+ [definitions.coverage]: 'Distinct covered code lines divided by the distinct code lines listed in LCOV DA records. Hit counts are summed across records. A zero denominator has no ratio.',
27
33
  [definitions.codeLines]: 'Nonblank physical lines after removing Babel comment spans and the interpreter directive. A line containing both code and a comment counts as code.',
28
34
  [definitions.comments]: 'Physical lines containing only a Babel comment or interpreter directive.',
29
35
  [definitions.classes]: 'Babel class declaration and expression nodes.',
@@ -32,29 +38,41 @@ const measurementDefinitions = {
32
38
  };
33
39
  export async function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths = [], coverage: inputCoverage }, additional = []) {
34
40
  const rows = [];
35
- const diagnostics = [];
41
+ const diagnostics = (snapshot.oversizedClaims ?? []).map(oversizedClaim);
36
42
  const findings = [];
37
43
  const cloneSources = [];
44
+ const sourceFiles = snapshot.files.filter(file => isSourcePath(file.path));
45
+ const claimedPlugins = [...securityPlugins.filter(plugin => !additional.includes(plugin)), ...additional];
38
46
  const enabled = [...sourcePlugins, duplication, ...(inputCoverage === undefined ? [] : [coverage])];
39
- const plugins = [...enabled, ...additional];
47
+ const plugins = [...enabled, ...claimedPlugins];
40
48
  if (additional.length)
41
49
  plan({ plugins, select: [], inputs: new Map() });
42
50
  if (inputCoverage === undefined && additional.some(plugin => plugin.id === coverage.id))
43
51
  throw new Error('An additional plugin uses a built-in plugin ID');
44
52
  const reportProducts = new ReportProducts(plugins);
45
- const sourcePlans = new Map([['', sourcePlan]]);
53
+ const sourcePlans = new Map([['[true]', sourcePlan]]);
46
54
  const usedPlans = new Map(sourcePlan.map(task => [task.key, task]));
47
- const matches = additional.map(plugin => claimMatcher(plugin.claims));
55
+ const matches = claimedPlugins.map(plugin => claimMatcher(plugin.claims));
48
56
  const parsed = new Set();
57
+ const inspected = new Set();
58
+ const scanned = new Set();
59
+ let completedFileInspection = false;
60
+ const scanOnlyOperations = new Set(plugins.filter(plugin => plugin.claims?.scanOnly).flatMap(({ id, operations }) => operations.map(operation => `${id}/${operation.id}`)));
61
+ const securityOperations = new Map(claimedPlugins.filter(plugin => plugin.kinds.includes('security')).flatMap(plugin => plugin.operations.filter(operation => operation.role === 'inspection').map(operation => [`${plugin.id}/${operation.id}`, plugin.id])));
49
62
  for (const file of snapshot.files) {
50
- const selectedPlugins = additional.filter((_, index) => matches[index](file.path));
51
- const group = JSON.stringify(selectedPlugins.map(plugin => plugin.id));
52
- const groupKey = selectedPlugins.length === 0 ? '' : group;
63
+ const source = isSourcePath(file.path);
64
+ const claimed = claimedPlugins.filter((_, index) => matches[index](file.path));
65
+ const selectedPlugins = isClaimedText(file.bytes) ? claimed : [];
66
+ if (claimed.length && file.bytes.byteLength > maxClaimedFileBytes)
67
+ diagnostics.push(oversizedClaim(file.path));
68
+ if (!source && !selectedPlugins.length)
69
+ continue;
70
+ const groupKey = JSON.stringify([source, ...selectedPlugins.map(plugin => plugin.id)]);
53
71
  const tasks = sourcePlans.get(groupKey) ?? plan({
54
- plugins: [...sourcePlugins, ...additional],
55
- select: [...selected, ...selectedPlugins.flatMap(plugin => plugin.operations
72
+ plugins: source ? [...sourcePlugins, ...claimedPlugins] : selectedPlugins,
73
+ select: [...(source ? selected : []), ...selectedPlugins.flatMap(plugin => plugin.operations
56
74
  .filter(operation => operation.role === 'inspection').map(operation => `${plugin.id}/${operation.id}`))],
57
- inputs: new Map([['file', sourceFile.id]]), bindings,
75
+ inputs: new Map([['file', sourceFile.id]]), ...(source ? { bindings } : {}),
58
76
  });
59
77
  sourcePlans.set(groupKey, tasks);
60
78
  const results = await execute(tasks, new Map([['file', { contract: sourceFile.id, value: file }]]));
@@ -73,7 +91,8 @@ export async function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths
73
91
  .get('duplication/detect');
74
92
  record(duplicationPlan[0], copies);
75
93
  if (inputCoverage !== undefined) {
76
- const value = { text: inputCoverage.text, root: inputCoverage.sourceRoot, sourceLines: sourceLineCounts(snapshot.files),
94
+ const value = { text: inputCoverage.text, root: inputCoverage.sourceRoot, sourceLines: sourceLineCounts(sourceFiles),
95
+ codeLines: new Map(cloneSources.map(({ path, codeLines }) => [path, new Set(codeLines)])),
77
96
  excludes: sourceExclusionMatcher(excludedPaths, snapshot.generatedExcluded) };
78
97
  const outcomes = await execute(coveragePlan, new Map([['lcov', { contract: lcovInput.id, value }]]));
79
98
  for (const task of coveragePlan)
@@ -86,6 +105,7 @@ export async function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths
86
105
  }
87
106
  }
88
107
  const pluginData = reportProducts.result();
108
+ const securityScanners = claimedPlugins.filter(plugin => scanned.has(plugin.id)).map(({ id, version }) => ({ name: id, version }));
89
109
  const inventory = new Map((snapshot.inventory ?? []).map(({ path, lines, bytes }) => [path, { lines, bytes }]));
90
110
  for (const { path, bytes } of snapshot.files) {
91
111
  if (!inventory.has(path))
@@ -101,20 +121,22 @@ export async function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths
101
121
  defaultExclusions: defaultSourceExclusions, generatedSourcePolicy, generatedExcluded: snapshot.generatedExcluded ?? [] },
102
122
  parser: parserDefaults,
103
123
  maintainability: { structuralRules, duplication: duplicationSettings, debtModel, remediation: 'nonoverlapping-complexity/v1' },
104
- coverage: inputCoverage === undefined ? null : { inputDigest: digest(inputCoverage.text), pathBase: inputCoverage.sourceRoot, merge: 'any-hit' },
124
+ coverage: inputCoverage === undefined ? null : { inputDigest: digest(inputCoverage.text), pathBase: inputCoverage.sourceRoot,
125
+ merge: 'any-hit', hitCounts: 'sum', lines: 'code-only' },
126
+ ...(securityScanners.length ? { securityScanners } : {}),
105
127
  plugins: plugins.map(({ id, version, api, tools, kinds, claims }) => ({ id, version, api, tools: tools ?? {}, ...(kinds === undefined ? {} : { kinds }), ...(claims === undefined ? {} : { claims }) })),
106
128
  operations: [...usedPlans.values(), ...duplicationPlan, ...(inputCoverage === undefined ? [] : coveragePlan)]
107
129
  .map(task => ({ key: task.key, inputs: Object.fromEntries(task.inputs) })),
108
130
  },
109
131
  definitions: { ...Object.fromEntries((pluginData?.metrics ?? []).map(metric => [metric.id, metric.description ?? metric.label])),
110
132
  ...measurementDefinitions },
111
- scope: { files: snapshot.files.length, parsed: parsed.size },
112
- status: diagnostics.length > 0 ? 'partial' : snapshot.files.length === 0 ? 'not-applicable' : 'complete',
133
+ scope: { files: sourceFiles.length, parsed: parsed.size },
134
+ status: diagnostics.length > 0 ? 'partial' : sourceFiles.length === 0 && !completedFileInspection ? 'not-applicable' : 'complete',
113
135
  measurements: rows,
114
136
  diagnostics,
115
137
  findings,
116
138
  ...(pluginData === undefined ? {} : { pluginData: { ...pluginData,
117
- inventory: [...inventory].sort(([left], [right]) => comparePaths(left, right)).map(([path, { lines, bytes }]) => ({ path, lines, ...(bytes === undefined ? {} : { bytes }), language: languageId(path), analysed: parsed.has(path) })) } }),
139
+ inventory: [...inventory].sort(([left], [right]) => comparePaths(left, right)).map(([path, { lines, bytes }]) => ({ path, lines, ...(bytes === undefined ? {} : { bytes }), language: languageId(path), analysed: parsed.has(path) || inspected.has(path) })) } }),
118
140
  };
119
141
  function record(task, outcome, path) {
120
142
  if (outcome.state !== 'completed') {
@@ -123,6 +145,14 @@ export async function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths
123
145
  }
124
146
  try {
125
147
  const stored = reportProducts.record(task, outcome.product, path);
148
+ if (path !== undefined && task.operation.role === 'inspection') {
149
+ completedFileInspection = true;
150
+ if (!scanOnlyOperations.has(task.key))
151
+ inspected.add(path);
152
+ }
153
+ const scanner = securityOperations.get(task.key);
154
+ if (scanner)
155
+ scanned.add(scanner);
126
156
  if (stored) {
127
157
  rows.push(...stored.measurements);
128
158
  findings.push(...stored.findings);
@@ -133,6 +163,9 @@ export async function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths
133
163
  }
134
164
  }
135
165
  }
166
+ function oversizedClaim(path) {
167
+ return { operation: 'source/claims', state: 'partial', path, message: 'Plugin inspection skipped a file larger than 1 MiB' };
168
+ }
136
169
  function languageId(path) {
137
170
  const suffix = extname(path).toLowerCase();
138
171
  if (['.js', '.mjs', '.cjs', '.jsx'].includes(suffix))
@@ -7,7 +7,7 @@ import { reportSchema } from '../core/model/report.js';
7
7
  import { isExcludedDirectory } from '../core/model/snapshot.js';
8
8
  import { executeInspection } from '../core/usecases/inspect.js';
9
9
  import { LocalReportStore } from '../report/json/store/local-store.js';
10
- import { analyzeSnapshot } from './analyze-snapshot.js';
10
+ import { analyzeSnapshot, claimsNativeFile } from './analyze-snapshot.js';
11
11
  import { attachChurn } from './attach-churn.js';
12
12
  export { analyzeSnapshot } from './analyze-snapshot.js';
13
13
  export async function inspect(request, overrides) {
@@ -23,7 +23,7 @@ export async function inspect(request, overrides) {
23
23
  return executeInspection(request, ports);
24
24
  }
25
25
  async function readSource(request, excludes) {
26
- const source = await readInspectionSource(request, excludes);
26
+ const source = await readInspectionSource(request, excludes, claimsNativeFile);
27
27
  const store = new LocalReportStore(source.output);
28
28
  return { ...source, save: (report) => store.save(report) };
29
29
  }
@@ -5,6 +5,7 @@ import { babelProvider } from '../plugins/language-js/babel-provider.js';
5
5
  import { maintainability } from '../plugins/maintainability/maintainability.js';
6
6
  import { structure } from '../plugins/structure/structure.js';
7
7
  import { sourceProviders } from './sources.js';
8
- export const builtInPlugins = [babelProvider, structure, maintainability, duplication, coverage, diffCoverage, ...sourceProviders]
8
+ import { securityPlugins } from './security-plugins.js';
9
+ export const builtInPlugins = [babelProvider, structure, maintainability, duplication, coverage, diffCoverage, ...securityPlugins, ...sourceProviders]
9
10
  .map(({ id, version, kinds, claims }) => ({ id, version, kinds, ...(claims ? { claims } : {}) }));
10
11
  //# sourceMappingURL=plugin-list.js.map
@@ -0,0 +1 @@
1
+ export declare const securityPlugins: import("../index.js").Plugin[];
@@ -0,0 +1,7 @@
1
+ import { jsSecurity } from '../plugins/language-js/js-security.js';
2
+ import { actionsSecurity } from '../plugins/security/actions-security.js';
3
+ import { dockerfile } from '../plugins/security/dockerfile.js';
4
+ import { npmSupplyChain } from '../plugins/security/npm-supply-chain.js';
5
+ import { secrets } from '../plugins/security/secrets.js';
6
+ export const securityPlugins = [secrets, jsSecurity, actionsSecurity, npmSupplyChain, dockerfile];
7
+ //# sourceMappingURL=security-plugins.js.map
@@ -27,8 +27,9 @@ export function manifestProducts(plugin, allowLegacy) {
27
27
  if (!strings(declaredKinds) || declaredKinds.length === 0 || declaredKinds.some(kind => !kinds.has(kind))) {
28
28
  throw new Error(`Invalid kinds for plugin ${id}`);
29
29
  }
30
- if (claims !== undefined && (!isRecord(claims) || Object.entries(claims).some(([key, values]) => !['extensions', 'globs', 'languages'].includes(key) || !strings(values)
31
- || (key === 'extensions' && values.some(extension => !/^\.[\w-]+$/.test(extension)))))) {
30
+ if (claims !== undefined && (!isRecord(claims) || Object.entries(claims).some(([key, values]) => key === 'scanOnly' ? typeof values !== 'boolean'
31
+ : !['extensions', 'globs', 'languages'].includes(key) || !strings(values)
32
+ || (key === 'extensions' && values.some(extension => !/^\.[\w-]+$/.test(extension)))))) {
32
33
  throw new Error(`Invalid file claims for plugin ${id}`);
33
34
  }
34
35
  if (!Array.isArray(produces))
@@ -36,6 +36,8 @@ export interface FileClaims {
36
36
  readonly extensions?: readonly string[];
37
37
  readonly globs?: readonly string[];
38
38
  readonly languages?: readonly string[];
39
+ /** Run inspections for matching files without counting them as analysed in the inventory. */
40
+ readonly scanOnly?: boolean;
39
41
  }
40
42
  export interface ProductDeclaration {
41
43
  readonly contract: string;
@@ -1,9 +1,11 @@
1
1
  import type { DataContract } from '../engine/plugin.js';
2
2
  export type CoveredLineRange = readonly [first: number, last: number];
3
+ export type HitRun = readonly [first: number, last: number, count: number];
3
4
  export interface FileLineCoverage {
4
5
  readonly covered: readonly CoveredLineRange[];
5
6
  readonly uncovered: readonly CoveredLineRange[];
6
7
  readonly partial?: readonly CoveredLineRange[];
8
+ readonly hits?: readonly HitRun[];
7
9
  }
8
10
  export type LineCoverage = Readonly<Record<string, FileLineCoverage>>;
9
11
  export declare const lcovLines: DataContract<LineCoverage>;
@@ -2,7 +2,7 @@ import { isRecord } from '../engine/plugin.js';
2
2
  export const lcovLines = {
3
3
  id: 'repometry.lcov-lines/v1',
4
4
  accepts: (value) => isRecord(value) && Object.values(value).every(file => isRecord(file) && isMerged(file.covered) && isMerged(file.uncovered) &&
5
- (file.partial === undefined || isMerged(file.partial))),
5
+ (file.partial === undefined || isMerged(file.partial)) && (file.hits === undefined || isMergedHits(file.hits))),
6
6
  };
7
7
  function isMerged(value) {
8
8
  if (!Array.isArray(value))
@@ -19,3 +19,21 @@ function isMerged(value) {
19
19
  }
20
20
  return true;
21
21
  }
22
+ function isMergedHits(value) {
23
+ if (!Array.isArray(value))
24
+ return false;
25
+ let previousEnd = 0;
26
+ let previousCount = -1;
27
+ for (const run of value) {
28
+ if (!Array.isArray(run) || run.length !== 3)
29
+ return false;
30
+ const [first, last, count] = run;
31
+ if (typeof first !== 'number' || typeof last !== 'number' || typeof count !== 'number' || !Number.isSafeInteger(first)
32
+ || !Number.isSafeInteger(last) || !Number.isSafeInteger(count) || first <= previousEnd || last < first || count < 0
33
+ || (first === previousEnd + 1 && count === previousCount))
34
+ return false;
35
+ previousEnd = last;
36
+ previousCount = count;
37
+ }
38
+ return true;
39
+ }
@@ -9,6 +9,8 @@ export interface SourceFile {
9
9
  readonly path: string;
10
10
  readonly bytes: Uint8Array;
11
11
  }
12
+ export declare const maxClaimedFileBytes: number;
13
+ export declare function isClaimedText(bytes: Uint8Array): boolean;
12
14
  export interface InventoryFile {
13
15
  readonly path: string;
14
16
  readonly lines: number | null;
@@ -20,4 +22,5 @@ export interface SourceSnapshot {
20
22
  readonly files: readonly SourceFile[];
21
23
  readonly inventory?: readonly InventoryFile[];
22
24
  readonly generatedExcluded?: readonly string[];
25
+ readonly oversizedClaims?: readonly string[];
23
26
  }
@@ -1 +1,4 @@
1
- export {};
1
+ export const maxClaimedFileBytes = 1024 * 1024;
2
+ export function isClaimedText(bytes) {
3
+ return bytes.byteLength <= maxClaimedFileBytes && !bytes.subarray(0, 8192).includes(0);
4
+ }