repometry 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) 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 +16 -9
  4. package/target/main/resources/viewer/styles.css +13 -2
  5. package/target/main/ts/api/git/git.d.ts +1 -1
  6. package/target/main/ts/api/git/git.js +21 -5
  7. package/target/main/ts/api/git/inspection-source.d.ts +1 -1
  8. package/target/main/ts/api/git/inspection-source.js +10 -4
  9. package/target/main/ts/api/git/local.d.ts +1 -1
  10. package/target/main/ts/api/git/local.js +29 -10
  11. package/target/main/ts/api/worker/worker-protocol.js +34 -9
  12. package/target/main/ts/compose/analyze-snapshot.d.ts +1 -0
  13. package/target/main/ts/compose/analyze-snapshot.js +50 -17
  14. package/target/main/ts/compose/inspect.js +2 -2
  15. package/target/main/ts/compose/plugin-list.js +2 -1
  16. package/target/main/ts/compose/security-plugins.d.ts +1 -0
  17. package/target/main/ts/compose/security-plugins.js +7 -0
  18. package/target/main/ts/core/engine/manifest.js +3 -2
  19. package/target/main/ts/core/engine/plugin.d.ts +2 -0
  20. package/target/main/ts/core/model/line-coverage.d.ts +2 -0
  21. package/target/main/ts/core/model/line-coverage.js +19 -1
  22. package/target/main/ts/core/model/source.d.ts +3 -0
  23. package/target/main/ts/core/model/source.js +4 -1
  24. package/target/main/ts/core/usecases/inspect.js +2 -2
  25. package/target/main/ts/plugins/coverage/coverage.d.ts +4 -3
  26. package/target/main/ts/plugins/coverage/coverage.js +46 -17
  27. package/target/main/ts/plugins/language-js/js-security.d.ts +4 -0
  28. package/target/main/ts/plugins/language-js/js-security.js +508 -0
  29. package/target/main/ts/plugins/security/actions-security.d.ts +2 -0
  30. package/target/main/ts/plugins/security/actions-security.js +581 -0
  31. package/target/main/ts/plugins/security/dockerfile.d.ts +2 -0
  32. package/target/main/ts/plugins/security/dockerfile.js +488 -0
  33. package/target/main/ts/plugins/security/npm-supply-chain.d.ts +4 -0
  34. package/target/main/ts/plugins/security/npm-supply-chain.js +368 -0
  35. package/target/main/ts/plugins/security/secrets.d.ts +12 -0
  36. package/target/main/ts/plugins/security/secrets.js +254 -0
  37. package/target/main/ts/report/html/app/viewer-files.d.ts +7 -0
  38. package/target/main/ts/report/html/app/viewer-files.js +60 -10
  39. package/target/main/ts/report/html/app/viewer-filter.js +8 -0
  40. package/target/main/ts/report/html/app/viewer-source.d.ts +17 -0
  41. package/target/main/ts/report/html/app/viewer-source.js +71 -11
  42. package/target/main/ts/report/html/site/badges.d.ts +1 -4
  43. package/target/main/ts/report/html/site/badges.js +28 -19
  44. package/target/main/ts/report/json/projections/commit-summary.js +2 -11
  45. package/target/main/ts/report/json/projections/inspection-context.js +6 -12
  46. package/target/main/ts/report/json/projections/security-summary.d.ts +11 -0
  47. 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.0",
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"],
@@ -428,6 +428,9 @@
428
428
  .fx-source { min-width: 0; padding: 0; overflow: hidden; }
429
429
  .fx-source-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .25rem 1rem; padding: .625rem 1rem; background: var(--band); border-bottom: 1px solid var(--rule); }
430
430
  .fx-source-path { min-width: 0; font-size: .8125rem; color: var(--ink); overflow-wrap: anywhere; }
431
+ .fx-source-name { display: inline-flex; align-items: center; gap: .125rem; min-width: 0; }
432
+ .fx-source-name .fx-copy-inline { position: static; flex: none; width: 1.5rem; height: 1.5rem; }
433
+ .fx-source-name .fx-copy-inline svg { width: .8125rem; height: .8125rem; }
431
434
  .fx-source-meta { display: inline-flex; align-items: center; gap: .375rem; font-size: .75rem; color: var(--secondary); }
432
435
  /* The switch between findings and coverage leads the head's right side; a narrow head wraps it under the name whole. */
433
436
  .fx-source-tools { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: .375rem .875rem; min-width: 0; }
@@ -446,18 +449,19 @@
446
449
  .src-number:hover { color: var(--ink); }
447
450
  .src-code { padding-right: 1.5rem; font: inherit; white-space: pre; color: var(--ink); }
448
451
  .src-flagged { background: var(--warn-bg); }
449
- /* Coverage replaces the findings on the lines: covered green, partly covered amber, missed red, unmeasured plain. The
450
- gutter says the same by shape, a full, half or empty dot, for readers who do not tell the tints apart. */
452
+ /* Coverage replaces the findings in the gutter and leaves the code plain: each measured line's cell is tinted, quiet
453
+ green where tests ran, coral where they missed, amber where they missed branches, and says how often it ran where
454
+ the report counts it; a miss needs no number. Blank and comment lines keep the strip's tint without a count; unmeasured lines
455
+ stay plain, and runs of lines join into one strip. */
451
456
  .src-cov { display: none; }
452
457
  .src[data-layer="coverage"] .src-complexity, .src[data-layer="coverage"] .src-note { display: none; }
453
458
  .src[data-layer="coverage"] .src-flagged { background: none; }
454
- .src[data-layer="coverage"] .src-cov-covered { background: var(--good-bg); }
455
- .src[data-layer="coverage"] .src-cov-partial { background: var(--warn-bg); }
456
- .src[data-layer="coverage"] .src-cov-uncovered { background: var(--bad-bg); }
457
- .src[data-layer="coverage"] .src-cov { display: block; width: .5rem; height: .5rem; border: 1.5px solid currentColor; border-radius: 50%; }
458
- .src-cov-mark-covered { color: var(--good); background: currentColor; }
459
- .src-cov-mark-partial { color: var(--grade-c); background: linear-gradient(90deg, currentColor 50%, transparent 50%); }
460
- .src-cov-mark-uncovered { color: var(--bad); }
459
+ .src[data-layer="coverage"] .src-line { grid-template-columns: 3.25rem 3rem max-content; }
460
+ .src[data-layer="coverage"] .src-cov { display: flex; flex: 1; align-self: stretch; align-items: center; justify-content: flex-end;
461
+ padding-right: .5rem; font-family: var(--sans); font-size: .6875rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
462
+ .src-cov-mark-covered { color: var(--cov-hit-ink); background: var(--cov-hit-bg); }
463
+ .src-cov-mark-partial { color: var(--cov-part-ink); background: var(--cov-part-bg); }
464
+ .src-cov-mark-uncovered { color: var(--cov-miss-ink); background: var(--cov-miss-bg); }
461
465
  .src-target, .src-target:hover { background: var(--accent-soft); box-shadow: inset 3px 0 0 var(--accent); }
462
466
  .src-complexity { min-width: 1.375rem; padding: 0 .25rem; font-family: var(--sans); font-size: .6875rem; font-weight: 650; line-height: 1.125rem; text-align: center; border-radius: 4px; color: var(--secondary); background: var(--surface-2); box-shadow: inset 0 0 0 1px var(--rule); }
463
467
  .src-band-1 { color: var(--heat-ink); background: var(--heat-1); box-shadow: none; }
@@ -499,6 +503,9 @@ code.fx-function-name { font-size: .75rem; color: var(--secondary); }
499
503
  .src-excerpt .src-line { grid-template-columns: .375rem 2.75rem max-content; }
500
504
  .src-excerpt .src-line:hover { background: transparent; }
501
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); }
502
509
  .src-more { display: block; padding: .1875rem 1rem .125rem 3.125rem; font-family: var(--sans); font-size: .75rem; }
503
510
 
504
511
  /* Map heading with its shape switch; the treemap's labels and folder frames. */
@@ -22,7 +22,13 @@
22
22
  --flag-good: #2f9445;
23
23
  --flag-bad: #c63d36;
24
24
  --bad-bg: #fdecea;
25
- --good-bg: #eff8f2;
25
+ /* Line coverage cells in the source gutter: a quiet green, coral for what tests missed, amber for missed branches. */
26
+ --cov-hit-bg: #e2f2e8;
27
+ --cov-hit-ink: #2f6e49;
28
+ --cov-miss-bg: #fbe2df;
29
+ --cov-miss-ink: #a8382e;
30
+ --cov-part-bg: #fbedcd;
31
+ --cov-part-ink: #7d5a10;
26
32
  --bad-ink: #9f2a21;
27
33
  --warn-bg: #fdf3dc;
28
34
  --warn-ink: #81580a;
@@ -87,7 +93,12 @@
87
93
  --flag-good: #5fd06a;
88
94
  --flag-bad: #f0736b;
89
95
  --bad-bg: #3a1c1a;
90
- --good-bg: #11231a;
96
+ --cov-hit-bg: #15301f;
97
+ --cov-hit-ink: #8fd0a9;
98
+ --cov-miss-bg: #3b1d1a;
99
+ --cov-miss-ink: #f0958c;
100
+ --cov-part-bg: #372a10;
101
+ --cov-part-ink: #e6c272;
91
102
  --bad-ink: #ffb1a8;
92
103
  --warn-bg: #352812;
93
104
  --warn-ink: #f2cd7f;
@@ -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;