@mitre/hdf-engine 3.7.1-rc.1 → 3.7.2-rc.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.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { impactToSeverity, validateInputSize, worstStatus } from "@mitre/hdf-utilities";
1
+ import { computeEffectiveImpact, extractCWEIDs, governingOverrideIndex, impactToSeverity, isGoZeroTime, parseTimestamp, validateInputSize, worstStatus } from "@mitre/hdf-utilities";
2
2
  import { parseBaseline, parseResults } from "@mitre/hdf-parsers";
3
3
  import { createHash } from "node:crypto";
4
4
  //#region src/version.ts
5
- const engineVersion = "3.7.1";
5
+ const engineVersion = "3.7.2";
6
6
  //#endregion
7
7
  //#region src/merge.ts
8
8
  /** Provenance label keys written on every merged baseline (ADR-0016 §3). */
@@ -157,6 +157,50 @@ function detect(input) {
157
157
  return "";
158
158
  }
159
159
  //#endregion
160
+ //#region src/effective.ts
161
+ /**
162
+ * Maps a requirement's schema overrides onto the shared helper's neutral shape,
163
+ * whose timestamps are the RFC3339 strings the schema's Date fields came from.
164
+ */
165
+ function overrideInputs(control) {
166
+ return (control.statusOverrides ?? []).map((o) => ({
167
+ status: o?.status,
168
+ appliedAt: rfc3339(o?.appliedAt),
169
+ expiresAt: rfc3339(o?.expiresAt),
170
+ impact: o?.impact?.value
171
+ }));
172
+ }
173
+ /**
174
+ * The schema types these as Date, but a parsed document carries the RFC3339
175
+ * strings they came from, so both shapes arrive here. A string passes through
176
+ * for the helper's parseTimestamp to read, which keeps a zone-less value UTC
177
+ * instead of host-local.
178
+ *
179
+ * Absent, unparseable, and Go's zero time all yield undefined, matching Go:
180
+ * its timestamps are non-pointer time.Time, so an unset one round-trips as
181
+ * 0001-01-01T00:00:00Z and decodes back to IsZero, and its ladder reads that as
182
+ * never expiring rather than as a real instant in year 1.
183
+ */
184
+ function rfc3339(value) {
185
+ if (!value) return void 0;
186
+ const parsed = typeof value === "string" ? parseTimestamp(value) : value;
187
+ if (parsed === null || Number.isNaN(parsed.getTime())) return void 0;
188
+ if (isGoZeroTime(parsed)) return void 0;
189
+ return typeof value === "string" ? value : parsed.toISOString();
190
+ }
191
+ /**
192
+ * The requirement's impact after its governing non-expired impact override, else
193
+ * its own. Computed rather than injected the way status is, because impact has
194
+ * no competing display conventions to reconcile — the ladder in hdf-utilities is
195
+ * canonical. An undefined reference means now.
196
+ */
197
+ function effectiveImpactOf(control, now) {
198
+ return computeEffectiveImpact({
199
+ impact: control.impact,
200
+ overrides: overrideInputs(control)
201
+ }, now);
202
+ }
203
+ //#endregion
160
204
  //#region src/compliance.ts
161
205
  /** Threshold status-key constants (SAF CLI-compatible keys). */
162
206
  const THRESHOLD_PASSED = "passed";
@@ -164,6 +208,12 @@ const THRESHOLD_FAILED = "failed";
164
208
  const THRESHOLD_SKIPPED = "skipped";
165
209
  const THRESHOLD_ERROR = "error";
166
210
  const THRESHOLD_NO_IMPACT = "no_impact";
211
+ /**
212
+ * The name the informational severity bucket had before 3.7.0 renamed it.
213
+ * Accepted on input and echoed back in violations written with it, never
214
+ * emitted by generate.
215
+ */
216
+ const LEGACY_INFORMATIONAL_KEY = "none";
167
217
  function newSeverityCounts() {
168
218
  return {
169
219
  critical: 0,
@@ -202,6 +252,26 @@ function deriveSeverity(impact, severity) {
202
252
  if (severity != null) return String(severity);
203
253
  return impactToSeverity(impact);
204
254
  }
255
+ /**
256
+ * severityBucket folds a severity string into the bucket the threshold grid
257
+ * counts it in. The schema's four named levels pass through; informational and
258
+ * anything outside the enum land in informational, so a malformed severity is
259
+ * counted rather than dropped and a document still gates.
260
+ *
261
+ * Exported because ControlIDMapping.severity is the bucket, not the raw string:
262
+ * a caller assembling its own control map has to apply the same rule or its
263
+ * listing and its counts will disagree. Parity: SeverityBucket in
264
+ * go/compliance.go.
265
+ */
266
+ function severityBucket(severity) {
267
+ switch (severity) {
268
+ case "critical":
269
+ case "high":
270
+ case "medium":
271
+ case "low": return severity;
272
+ default: return "informational";
273
+ }
274
+ }
205
275
  function statusBucket(counts, status) {
206
276
  switch (status) {
207
277
  case "passed": return counts.passed;
@@ -215,7 +285,7 @@ function statusBucket(counts, status) {
215
285
  function addCount(counts, status, severity) {
216
286
  const sc = statusBucket(counts, status);
217
287
  sc.total++;
218
- switch (severity) {
288
+ switch (severityBucket(severity)) {
219
289
  case "critical":
220
290
  sc.critical++;
221
291
  break;
@@ -231,6 +301,24 @@ function addCount(counts, status, severity) {
231
301
  default: sc.informational++;
232
302
  }
233
303
  }
304
+ /**
305
+ * statusToThresholdKey's inverse, for reporting a requirement found via the
306
+ * control map. A finding line describes the REQUIREMENT, so it names the
307
+ * requirement's own status — which is also the only vocabulary
308
+ * `hdf query --status` accepts, so a reader can paste the value straight into a
309
+ * query. The threshold key is a bucket name and is refused there.
310
+ * Parity: thresholdKeyToStatus in go/compliance.go.
311
+ */
312
+ function thresholdKeyToStatus(key) {
313
+ switch (key) {
314
+ case THRESHOLD_PASSED: return "passed";
315
+ case THRESHOLD_FAILED: return "failed";
316
+ case THRESHOLD_SKIPPED: return "notReviewed";
317
+ case THRESHOLD_ERROR: return "error";
318
+ case THRESHOLD_NO_IMPACT: return "notApplicable";
319
+ default: return key;
320
+ }
321
+ }
234
322
  function statusToThresholdKey(status) {
235
323
  switch (status) {
236
324
  case "passed": return THRESHOLD_PASSED;
@@ -241,7 +329,11 @@ function statusToThresholdKey(status) {
241
329
  default: return THRESHOLD_SKIPPED;
242
330
  }
243
331
  }
244
- /** CountControlsByStatusSeverity counts requirements by overall status and severity. */
332
+ /**
333
+ * countControlsByStatusSeverity counts requirements by overall status and severity.
334
+ * Reads each requirement's OWN impact and raw result statuses by design: this is the
335
+ * no-override-awareness twin of countControlsByStatus, which is its purpose.
336
+ */
245
337
  function countControlsByStatusSeverity(results) {
246
338
  const counts = newStatusCounts();
247
339
  for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) addCount(counts, overallStatus(req.results ?? []), deriveSeverity(req.impact, reqSeverity(req)));
@@ -257,9 +349,9 @@ function countControlsByStatusSeverity(results) {
257
349
  * (e.g. compliance with and without agent-attributed overrides) without the
258
350
  * engine binding to any one status convention. Parity: go/compliance.go.
259
351
  */
260
- function countControlsByStatus(results, statusOf) {
352
+ function countControlsByStatus(results, statusOf, now) {
261
353
  const counts = newStatusCounts();
262
- for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) addCount(counts, statusOf ? statusOf(req) : "", deriveSeverity(req.impact, reqSeverity(req)));
354
+ for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) addCount(counts, statusOf ? statusOf(req) : "", deriveSeverity(effectiveImpactOf(req, now), reqSeverity(req)));
263
355
  return counts;
264
356
  }
265
357
  /**
@@ -281,7 +373,8 @@ function mapControlIDs(results) {
281
373
  mappings.push({
282
374
  id: req.id,
283
375
  status: statusToThresholdKey(status),
284
- severity: deriveSeverity(req.impact, reqSeverity(req))
376
+ severity: severityBucket(deriveSeverity(req.impact, reqSeverity(req))),
377
+ title: req.title ?? ""
285
378
  });
286
379
  }
287
380
  return mappings;
@@ -295,14 +388,15 @@ function mapControlIDs(results) {
295
388
  * listings (the same injection pattern as countControlsByStatus). Parity:
296
389
  * go/compliance.go MapControlIDsByStatus.
297
390
  */
298
- function mapControlIDsByStatus(results, statusOf) {
391
+ function mapControlIDsByStatus(results, statusOf, now) {
299
392
  const mappings = [];
300
393
  for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) {
301
394
  const status = statusOf ? statusOf(req) : "";
302
395
  mappings.push({
303
396
  id: req.id,
304
397
  status: statusToThresholdKey(status),
305
- severity: deriveSeverity(req.impact, reqSeverity(req))
398
+ severity: severityBucket(deriveSeverity(effectiveImpactOf(req, now), reqSeverity(req))),
399
+ title: req.title ?? ""
306
400
  });
307
401
  }
308
402
  return mappings;
@@ -311,6 +405,117 @@ function reqSeverity(req) {
311
405
  return req.severity ?? null;
312
406
  }
313
407
  /**
408
+ * normalizeThresholdConfig folds SAF's scalar count bound into the object form a
409
+ * bound is otherwise written in: a bare `total: 19` means EXACTLY 19, measured in
410
+ * SAF's own validate-threshold command, which guards the scalar path with
411
+ * `typeof !== 'object'` and then fails on inequality.
412
+ *
413
+ * Go reaches this rule through ThresholdBound's YAML decoding; TypeScript does no
414
+ * YAML decoding of its own, so a consumer that parsed a SAF file itself calls
415
+ * this before evaluating. Both are pinned by testdata/saf-bound-shorthand-cases.json.
416
+ * The input is not mutated.
417
+ */
418
+ function normalizeThresholdConfig(config) {
419
+ const bound = (value) => {
420
+ if (value === void 0 || value === null) return void 0;
421
+ if (typeof value === "number") {
422
+ if (!Number.isInteger(value)) throw new Error(`a bound written as a bare value must be a whole number of controls, got ${value}`);
423
+ return {
424
+ min: value,
425
+ max: value
426
+ };
427
+ }
428
+ if (typeof value !== "object" || Array.isArray(value)) throw new Error(`a bound must be a whole number of controls or a min/max mapping, got ${JSON.stringify(value)}`);
429
+ for (const [key, v] of Object.entries(value)) if (key === "min" || key === "max") {
430
+ if (!Number.isInteger(v)) throw new Error(`a bound's ${key} must be a whole number of controls, got ${JSON.stringify(v)}`);
431
+ } else if (key === "controls") {
432
+ if (!Array.isArray(v) || !v.every((x) => typeof x === "string")) throw new Error(`a bound's controls must be a list of control ids, got ${JSON.stringify(v)}`);
433
+ } else throw new Error(`field ${key} is not a known bound`);
434
+ return value;
435
+ };
436
+ const section = (ts) => {
437
+ if (!ts) return ts;
438
+ const out = {};
439
+ for (const key of [
440
+ "critical",
441
+ "high",
442
+ "medium",
443
+ "low",
444
+ "informational",
445
+ "none",
446
+ "total"
447
+ ]) {
448
+ const normalized = bound(ts[key]);
449
+ if (normalized !== void 0) out[key] = normalized;
450
+ }
451
+ return out;
452
+ };
453
+ return {
454
+ ...config,
455
+ passed: section(config.passed),
456
+ failed: section(config.failed),
457
+ skipped: section(config.skipped),
458
+ error: section(config.error),
459
+ noImpact: section(config.noImpact)
460
+ };
461
+ }
462
+ /**
463
+ * A count set's five status buckets, so a bucket-wise operation is written once
464
+ * and cannot miss one. Parity: statusBuckets in go/compliance.go.
465
+ */
466
+ function statusBuckets(counts) {
467
+ return [
468
+ counts.passed,
469
+ counts.failed,
470
+ counts.skipped,
471
+ counts.error,
472
+ counts.noImpact
473
+ ];
474
+ }
475
+ function addSeverities(dst, src) {
476
+ dst.critical += src.critical;
477
+ dst.high += src.high;
478
+ dst.medium += src.medium;
479
+ dst.low += src.low;
480
+ dst.informational += src.informational;
481
+ dst.total += src.total;
482
+ }
483
+ /**
484
+ * addCounts sums count sets bucket by bucket and severity by severity, returning
485
+ * a new set and leaving its arguments untouched — a caller that reports the parts
486
+ * beside the whole is summing the very objects it still has to print. Each
487
+ * bucket's `total` is added, never recomputed from the severity fields.
488
+ *
489
+ * The counting functions above measure one document at a time, so a caller that
490
+ * composes documents — the HTML report rolling baselines into a source and
491
+ * sources into a whole, each evaluated as of its own assessment time — needs this
492
+ * rather than a second counting pass. Combining whole DOCUMENTS is merge's job,
493
+ * not this function's (ADR-0016 §1). Parity: AddCounts in go/compliance.go,
494
+ * pinned by testdata/status-counts-rollup-cases.json.
495
+ */
496
+ function addCounts(...counts) {
497
+ const out = newStatusCounts();
498
+ const dst = statusBuckets(out);
499
+ for (const c of counts) {
500
+ if (c == null) continue;
501
+ statusBuckets(c).forEach((bucket, i) => addSeverities(dst[i], bucket));
502
+ }
503
+ return out;
504
+ }
505
+ /**
506
+ * severityTotals projects a count set onto severity alone, summing each severity
507
+ * across every status — so `total` is the whole set's requirement count. A
508
+ * severity breakdown answers "how much risk is in this document", which is a
509
+ * question about all of it, not about its failures. Parity: SeverityTotals in
510
+ * go/compliance.go.
511
+ */
512
+ function severityTotals(counts) {
513
+ const out = newSeverityCounts();
514
+ if (counts == null) return out;
515
+ for (const bucket of statusBuckets(counts)) addSeverities(out, bucket);
516
+ return out;
517
+ }
518
+ /**
314
519
  * calculateCompliance returns the compliance percentage rounded to two decimals:
315
520
  * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.
316
521
  */
@@ -321,62 +526,171 @@ function calculateCompliance(counts) {
321
526
  return Math.round(pct * 100) / 100;
322
527
  }
323
528
  /**
324
- * normalizeLegacySeverity folds the pre-3.7 `none` key into `informational`. A
325
- * spec setting both is refused rather than resolved: the two name one bucket, so
326
- * silently honouring one would drop a bound the author wrote.
529
+ * resolveLegacySeverity folds a section's pre-3.7 `none` key into
530
+ * `informational`, reporting whether the bound was written that way so a
531
+ * violation can name the key the author will find in their own file. A spec
532
+ * setting both is refused rather than resolved: 3.7.0 renamed the bucket, so the
533
+ * two name one thing and silently honouring one would drop a bound the author
534
+ * wrote.
535
+ *
536
+ * The caller's section is COPIED, never rewritten. Folding in place made the
537
+ * name a one-shot property of the config object: the same spec reported the
538
+ * author's key on its first validate pass and the canonical one on every pass
539
+ * after, which is the confusion naming the author's key exists to remove.
540
+ * Parity: resolveLegacySeverity in go/compliance.go.
327
541
  */
328
- function normalizeLegacySeverity(config) {
329
- const violations = [];
330
- const sections = [
331
- [THRESHOLD_PASSED, config.passed],
332
- [THRESHOLD_FAILED, config.failed],
333
- [THRESHOLD_SKIPPED, config.skipped],
334
- [THRESHOLD_ERROR, config.error],
335
- [THRESHOLD_NO_IMPACT, config.noImpact]
336
- ];
337
- for (const [name, ts] of sections) {
338
- if (!ts?.none) continue;
339
- if (ts.informational) {
340
- violations.push(`${name}: both 'none' and 'informational' are set; 'none' is the pre-3.7 spelling of the same bucket`);
341
- continue;
342
- }
343
- ts.informational = ts.none;
344
- delete ts.none;
345
- }
346
- return violations;
542
+ function resolveLegacySeverity(name, ts) {
543
+ if (!ts?.none) return {
544
+ threshold: ts,
545
+ wroteNone: false,
546
+ refusal: ""
547
+ };
548
+ if (ts.informational) return {
549
+ threshold: ts,
550
+ wroteNone: false,
551
+ refusal: `${name}: both 'none' and 'informational' are set; 'informational' replaced 'none' in 3.7.0 and both name the same bucket`
552
+ };
553
+ const resolved = {
554
+ ...ts,
555
+ informational: ts.none
556
+ };
557
+ delete resolved.none;
558
+ return {
559
+ threshold: resolved,
560
+ wroteNone: true,
561
+ refusal: ""
562
+ };
563
+ }
564
+ /** The messages of a violation list, for a caller that wants the verdict alone. */
565
+ function violationMessages(violations) {
566
+ return violations.map((v) => v.message);
347
567
  }
348
568
  /**
349
569
  * validateThresholds checks all threshold bounds against observed counts and
350
570
  * compliance, returning human-readable violation messages (empty when all pass).
351
571
  */
352
572
  function validateThresholds(config, counts, compliance, controlMap) {
573
+ const violations = violationMessages(validateGrid(config, counts, compliance, controlMap));
574
+ if (config.rules && config.rules.length > 0) violations.push(ruleRefusal(config.rules.length));
575
+ return violations;
576
+ }
577
+ /**
578
+ * ruleRefusal is what a caller is told when a policy carries rules the path it
579
+ * used cannot evaluate. It reaches end users, so it names the spec and what to do
580
+ * about it rather than an internal function. Parity: ruleRefusal in go/rules.go.
581
+ */
582
+ function ruleRefusal(count) {
583
+ return `this spec declares ${count} ${count === 1 ? "rule" : "rules"}, which this evaluation path cannot apply; the tool must evaluate rules against the document, not against counts alone`;
584
+ }
585
+ /**
586
+ * validateGrid is the status x severity half of a policy, shared by
587
+ * validateThresholds and evaluate. Parity: validateGrid in go/compliance.go.
588
+ */
589
+ function validateGrid(config, counts, compliance, controlMap) {
353
590
  const violations = [];
354
- violations.push(...normalizeLegacySeverity(config));
591
+ config = normalizeThresholdConfig(config);
592
+ const sections = [
593
+ {
594
+ name: THRESHOLD_PASSED,
595
+ threshold: config.passed,
596
+ counts: counts.passed,
597
+ wroteNone: false
598
+ },
599
+ {
600
+ name: THRESHOLD_FAILED,
601
+ threshold: config.failed,
602
+ counts: counts.failed,
603
+ wroteNone: false
604
+ },
605
+ {
606
+ name: THRESHOLD_SKIPPED,
607
+ threshold: config.skipped,
608
+ counts: counts.skipped,
609
+ wroteNone: false
610
+ },
611
+ {
612
+ name: THRESHOLD_ERROR,
613
+ threshold: config.error,
614
+ counts: counts.error,
615
+ wroteNone: false
616
+ },
617
+ {
618
+ name: THRESHOLD_NO_IMPACT,
619
+ threshold: config.noImpact,
620
+ counts: counts.noImpact,
621
+ wroteNone: false
622
+ }
623
+ ];
624
+ for (const section of sections) {
625
+ const { threshold, wroteNone, refusal } = resolveLegacySeverity(section.name, section.threshold);
626
+ if (refusal) violations.push({
627
+ message: refusal,
628
+ findings: []
629
+ });
630
+ section.threshold = threshold;
631
+ section.wroteNone = wroteNone;
632
+ }
355
633
  const actualControls = /* @__PURE__ */ new Map();
356
- for (const m of controlMap) actualControls.set(m.id, m);
634
+ for (const m of controlMap) {
635
+ const existing = actualControls.get(m.id);
636
+ if (existing) existing.push(m);
637
+ else actualControls.set(m.id, [m]);
638
+ }
357
639
  if (config.compliance) {
358
- if (config.compliance.min !== void 0 && compliance < config.compliance.min) violations.push(`compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`);
359
- if (config.compliance.max !== void 0 && compliance > config.compliance.max) violations.push(`compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`);
360
- }
361
- violations.push(...checkSeverityThreshold(THRESHOLD_PASSED, config.passed, counts.passed, actualControls));
362
- violations.push(...checkSeverityThreshold(THRESHOLD_FAILED, config.failed, counts.failed, actualControls));
363
- violations.push(...checkSeverityThreshold(THRESHOLD_SKIPPED, config.skipped, counts.skipped, actualControls));
364
- violations.push(...checkSeverityThreshold(THRESHOLD_ERROR, config.error, counts.error, actualControls));
365
- violations.push(...checkSeverityThreshold(THRESHOLD_NO_IMPACT, config.noImpact, counts.noImpact, actualControls));
640
+ if (config.compliance.min !== void 0 && compliance < config.compliance.min) violations.push({
641
+ message: `compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`,
642
+ findings: []
643
+ });
644
+ if (config.compliance.max !== void 0 && compliance > config.compliance.max) violations.push({
645
+ message: `compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`,
646
+ findings: []
647
+ });
648
+ }
649
+ for (const section of sections) violations.push(...checkSeverityThreshold(section.name, section.threshold, section.counts, actualControls, section.wroteNone, controlMap));
366
650
  return violations;
367
651
  }
368
- function checkSeverityThreshold(status, threshold, actual, actualControls) {
652
+ function checkSeverityThreshold(status, threshold, actual, actualControls, wroteNone, controlMap) {
369
653
  if (!threshold) return [];
654
+ const pathLabel = (label) => wroteNone && label === "informational" ? LEGACY_INFORMATIONAL_KEY : label;
655
+ const inBucket = (label) => controlMap.filter((m) => m.status === status && (label === "total" || m.severity === label)).map((m) => ({
656
+ id: m.id,
657
+ title: m.title ?? "",
658
+ status: thresholdKeyToStatus(m.status),
659
+ impact: 0,
660
+ severity: m.severity,
661
+ baseline: "",
662
+ baselineIndex: 0,
663
+ index: 0
664
+ }));
370
665
  const violations = [];
371
666
  const check = (label, bound, actualCount) => {
372
667
  if (!bound) return;
373
- const path = `${status}.${label}`;
374
- if (bound.min !== void 0 && actualCount < bound.min) violations.push(`${path}: ${actualCount} is below minimum ${bound.min}`);
375
- if (bound.max !== void 0 && actualCount > bound.max) violations.push(`${path}: ${actualCount} exceeds maximum ${bound.max}`);
668
+ const path = `${status}.${pathLabel(label)}`;
669
+ if (bound.min !== void 0 && actualCount < bound.min) violations.push({
670
+ message: `${path}: ${actualCount} is below minimum ${bound.min}`,
671
+ findings: inBucket(label)
672
+ });
673
+ if (bound.max !== void 0 && actualCount > bound.max) violations.push({
674
+ message: `${path}: ${actualCount} exceeds maximum ${bound.max}`,
675
+ findings: inBucket(label)
676
+ });
376
677
  for (const expectedID of bound.controls ?? []) {
377
- const ac = actualControls.get(expectedID);
378
- if (!ac) violations.push(`${path}: expected control ${expectedID} not found in results`);
379
- else if (ac.status !== status || ac.severity !== label) violations.push(`${path}: control ${expectedID} expected ${status}/${label} but found ${ac.status}/${ac.severity}`);
678
+ const matches = actualControls.get(expectedID) ?? [];
679
+ if (matches.length === 0) {
680
+ violations.push({
681
+ message: `${path}: expected control ${expectedID} not found in results`,
682
+ findings: []
683
+ });
684
+ continue;
685
+ }
686
+ matches.forEach((ac, i) => {
687
+ if (ac.status === status && ac.severity === label) return;
688
+ const entry = matches.length > 1 ? ` (entry ${i + 1} of ${matches.length})` : "";
689
+ violations.push({
690
+ message: `${path}: control ${expectedID} expected ${status}/${label} but found ${ac.status}/${ac.severity}${entry}`,
691
+ findings: []
692
+ });
693
+ });
380
694
  }
381
695
  };
382
696
  check("critical", threshold.critical, actual.critical);
@@ -388,6 +702,122 @@ function checkSeverityThreshold(status, threshold, actual, actualControls) {
388
702
  return violations;
389
703
  }
390
704
  //#endregion
705
+ //#region src/vocabulary.ts
706
+ /**
707
+ * The closed vocabulary a status filter may name: the schema's Result_Status
708
+ * enum. It is the EFFECTIVE status that is compared — the resolver a caller
709
+ * injects runs the override ladder first — so these are the values a requirement
710
+ * can present after its amendments are applied.
711
+ */
712
+ const STATUS_VALUES = [
713
+ "passed",
714
+ "failed",
715
+ "notApplicable",
716
+ "notReviewed",
717
+ "error"
718
+ ];
719
+ /** The schema's Severity enum, which is also what deriveSeverity returns. */
720
+ const SEVERITY_VALUES = [
721
+ "critical",
722
+ "high",
723
+ "medium",
724
+ "low",
725
+ "informational"
726
+ ];
727
+ const STATUS_ALIAS_LIST = [{
728
+ form: "not_applicable",
729
+ means: "notApplicable",
730
+ advertise: true
731
+ }, {
732
+ form: "not_reviewed",
733
+ means: "notReviewed",
734
+ advertise: true
735
+ }];
736
+ const SEVERITY_ALIAS_LIST = [{
737
+ form: "none",
738
+ means: "informational",
739
+ advertise: false
740
+ }];
741
+ const DISPOSITION_ALIAS_LIST = [{
742
+ form: "false_positive",
743
+ means: "falsePositive",
744
+ advertise: true
745
+ }];
746
+ /** Derived from the lists, so an alias cannot be accepted without declaring whether it is advertised. */
747
+ function aliasMap(aliases) {
748
+ return Object.fromEntries(aliases.map((a) => [a.form, a.means]));
749
+ }
750
+ const STATUS_ALIASES = aliasMap(STATUS_ALIAS_LIST);
751
+ const SEVERITY_ALIASES = aliasMap(SEVERITY_ALIAS_LIST);
752
+ const DISPOSITION_ALIASES = aliasMap(DISPOSITION_ALIAS_LIST);
753
+ /** The accepted non-canonical forms for a field, or undefined when it has no closed vocabulary. */
754
+ function filterAliases(field) {
755
+ switch (field) {
756
+ case "status": return STATUS_ALIAS_LIST;
757
+ case "severity": return SEVERITY_ALIAS_LIST;
758
+ case "disposition": return DISPOSITION_ALIAS_LIST;
759
+ default: return;
760
+ }
761
+ }
762
+ /** The canonical vocabulary for a field, or undefined when it has no closed one. */
763
+ function filterValues(field) {
764
+ switch (field) {
765
+ case "status": return STATUS_VALUES;
766
+ case "severity": return SEVERITY_VALUES;
767
+ case "disposition": return DISPOSITION_VALUES;
768
+ default: return;
769
+ }
770
+ }
771
+ /**
772
+ * The forms a help string or tool schema should name for a field: the canonical
773
+ * vocabulary, then the aliases marked for teaching. Every value here is accepted,
774
+ * but not everything accepted is here — a retired name is deliberately absent.
775
+ * Parity: AdvertisedFilterValues in go/vocabulary.go.
776
+ */
777
+ function advertisedFilterValues(field) {
778
+ const canonical = filterValues(field);
779
+ if (!canonical) return void 0;
780
+ return [...canonical, ...(filterAliases(field) ?? []).filter((a) => a.advertise).map((a) => a.form)];
781
+ }
782
+ /**
783
+ * Folds a value to the form comparisons use. Case only: two spellings are the
784
+ * same value because this file says so, not because enough punctuation was
785
+ * removed to make them collide.
786
+ */
787
+ function normalizeKey(s) {
788
+ return s.trim().toLowerCase();
789
+ }
790
+ function canonical(vocabulary, aliases, value) {
791
+ const key = normalizeKey(value);
792
+ if (aliases && aliases[key]) return aliases[key];
793
+ return vocabulary.find((member) => normalizeKey(member) === key) ?? "";
794
+ }
795
+ /** Whether s names a status the filter understands, in any accepted form. */
796
+ function validStatus(s) {
797
+ return canonical(STATUS_VALUES, STATUS_ALIASES, s) !== "";
798
+ }
799
+ /** Whether s names a severity the filter understands, in any accepted form. */
800
+ function validSeverity(s) {
801
+ return canonical(SEVERITY_VALUES, SEVERITY_ALIASES, s) !== "";
802
+ }
803
+ /**
804
+ * The canonical form of a filter value for the named field, or the value
805
+ * unchanged when the field has no closed vocabulary or the value names no
806
+ * member. Normalizing here rather than in one caller is what makes a threshold
807
+ * rule and an `hdf query` invocation mean the same thing.
808
+ */
809
+ function normalizeFilterValue(field, value) {
810
+ switch (field) {
811
+ case "status": return canonical(STATUS_VALUES, STATUS_ALIASES, value) || value;
812
+ case "severity": return canonical(SEVERITY_VALUES, SEVERITY_ALIASES, value) || value;
813
+ case "disposition": return canonical(DISPOSITION_VALUES, DISPOSITION_ALIASES, value) || value;
814
+ case "poams":
815
+ if (!validPoamFilter(value)) return value;
816
+ return normalizeKey(value) === normalizeKey("valid") ? POAM_VALID : POAM_NONE_VALID;
817
+ default: return value;
818
+ }
819
+ }
820
+ //#endregion
391
821
  //#region src/safematch.ts
392
822
  const MAX_PATTERN_LENGTH = 256;
393
823
  const REGEX_SPECIAL = /* @__PURE__ */ new Set([
@@ -442,27 +872,81 @@ function safeGlobMatch(s, pattern) {
442
872
  return re.test(s);
443
873
  }
444
874
  //#endregion
875
+ //#region src/values.ts
876
+ /** Whether the field constrains anything at all. */
877
+ function valuesActive(v) {
878
+ return v !== void 0 && (v.in.length > 0 || v.not.length > 0);
879
+ }
880
+ /**
881
+ * Applies the field's own per-value test. `test` reports whether the requirement
882
+ * matches ONE named value; this combines those the way the vocabulary always has
883
+ * — values within a field OR — and then applies the exclusion.
884
+ */
885
+ function valuesMatch(v, test) {
886
+ if (v.in.length > 0 && !v.in.some(test)) return false;
887
+ if (v.not.length > 0 && v.not.some(test)) return false;
888
+ return true;
889
+ }
890
+ /**
891
+ * Normalizes whatever a policy carried into a Values. Throws on a shape that is
892
+ * none of the three, so a malformed predicate is refused rather than silently
893
+ * asserting nothing. Parity: Values.UnmarshalYAML / UnmarshalJSON in
894
+ * go/values.go, and the shared case table pins the accepted forms.
895
+ */
896
+ function normalizeValues(raw) {
897
+ if (raw === void 0 || raw === null) return {
898
+ in: [],
899
+ not: []
900
+ };
901
+ if (typeof raw === "string") return {
902
+ in: [raw],
903
+ not: []
904
+ };
905
+ if (Array.isArray(raw)) {
906
+ if (!raw.every((v) => typeof v === "string")) throw new Error("a predicate value is a value, a list, or {not: ...}");
907
+ return {
908
+ in: raw,
909
+ not: []
910
+ };
911
+ }
912
+ if (typeof raw === "object") {
913
+ const other = Object.keys(raw).find((k) => k !== "not");
914
+ if (other !== void 0) throw new Error(`field "${other}" is not a known form; a predicate value is a value, a list, or {not: ...}`);
915
+ const inner = normalizeValues(raw.not);
916
+ if (inner.not.length > 0) throw new Error("not cannot be nested inside not");
917
+ if (inner.in.length === 0) throw new Error("not excludes nothing; a predicate that asserts nothing is refused");
918
+ return {
919
+ in: [],
920
+ not: inner.in
921
+ };
922
+ }
923
+ throw new Error("a predicate value is a value, a list, or {not: ...}");
924
+ }
925
+ //#endregion
445
926
  //#region src/query.ts
446
927
  /**
447
928
  * filter returns the requirements across the result set's baselines that satisfy
448
929
  * options. Applies to requirement collections (results/baseline documents); the
449
930
  * calling adapter rejects document types that carry no requirements.
450
931
  */
451
- function filter(results, options) {
932
+ function filter(results, rawOptions) {
933
+ const options = normalizeOptions(rawOptions);
452
934
  const filters = buildFilters(options);
453
935
  const matches = [];
454
936
  for (const [baselineIndex, baseline] of (results.baselines ?? []).entries()) {
455
937
  if (options.baseline && !matchesGlob(baseline.name, options.baseline)) continue;
938
+ if (!baselineLabelsMatch(baseline.labels, options.baselineLabel)) continue;
456
939
  for (const [index, control] of (baseline.requirements ?? []).entries()) {
457
940
  if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) return matches;
458
941
  const status = options.statusOf ? options.statusOf(control) : "";
459
- const severity = deriveSeverity(control.impact, control.severity ?? null);
942
+ const impact = effectiveImpactOf(control, options.now);
943
+ const severity = deriveSeverity(impact, control.severity ?? null);
460
944
  if (!applyFilters(control, status, severity, filters)) continue;
461
945
  matches.push({
462
946
  id: control.id,
463
947
  title: control.title ?? "",
464
948
  status,
465
- impact: control.impact,
949
+ impact,
466
950
  severity,
467
951
  baseline: baseline.name,
468
952
  baselineIndex,
@@ -472,43 +956,83 @@ function filter(results, options) {
472
956
  }
473
957
  return matches;
474
958
  }
959
+ const VALUE_FIELDS = [
960
+ "status",
961
+ "severity",
962
+ "cwe",
963
+ "cci",
964
+ "nist",
965
+ "tag",
966
+ "baselineLabel",
967
+ "disposition",
968
+ "poamType"
969
+ ];
970
+ function normalizeOptions(options) {
971
+ const out = { ...options };
972
+ for (const field of VALUE_FIELDS) if (out[field] !== void 0) out[field] = normalizeValues(out[field]);
973
+ return out;
974
+ }
475
975
  function buildFilters(options) {
476
976
  const filters = [];
477
- if (options.status && options.status.length > 0) {
478
- const statuses = options.status.map((s) => s.toLowerCase());
479
- filters.push((_c, s) => statuses.includes(s.toLowerCase()));
480
- }
481
- if (options.severity && options.severity.length > 0) {
482
- const severities = options.severity.map((s) => s.toLowerCase());
483
- filters.push((_c, _s, severity) => severities.includes(severity));
977
+ if (valuesActive(options.status)) filters.push((_c, s) => {
978
+ const actual = normalizeKey(normalizeFilterValue("status", s));
979
+ return valuesMatch(options.status, (want) => actual === normalizeKey(normalizeFilterValue("status", want)));
980
+ });
981
+ if (valuesActive(options.severity)) filters.push((_c, _s, severity) => {
982
+ const actual = normalizeKey(normalizeFilterValue("severity", severity));
983
+ return valuesMatch(options.severity, (want) => actual === normalizeKey(normalizeFilterValue("severity", want)));
984
+ });
985
+ if (valuesActive(options.disposition)) filters.push((c) => {
986
+ const governing = governingDisposition(c, options.now);
987
+ const actual = normalizeKey(normalizeFilterValue("disposition", governing));
988
+ return valuesMatch(options.disposition, (want) => governing !== "" && actual === normalizeKey(normalizeFilterValue("disposition", want)));
989
+ });
990
+ if (valuesActive(options.poamType)) filters.push((c) => {
991
+ const kind = governingPoamType(c, options.now);
992
+ return valuesMatch(options.poamType, (want) => kind !== "" && normalizeKey(kind) === normalizeKey(want));
993
+ });
994
+ if (options.poams) {
995
+ const wantValid = poamFilterWantsValid(options.poams);
996
+ filters.push((c) => wantValid !== void 0 && hasValidPoam(c, options.now) === wantValid);
484
997
  }
485
998
  if (options.impact) {
486
999
  const [op, val] = parseImpactFilter(options.impact);
1000
+ filters.push((c) => compareImpact(effectiveImpactOf(c, options.now), op, val));
1001
+ }
1002
+ if (options.rawImpact) {
1003
+ const [op, val] = parseImpactFilter(options.rawImpact);
487
1004
  filters.push((c) => compareImpact(c.impact, op, val));
488
1005
  }
489
- if (options.cci && options.cci.length > 0) {
490
- const ccis = options.cci.map((c) => c.toUpperCase());
491
- filters.push((c) => ccis.some((cci) => tagContains(c.tags, "cci", cci)));
1006
+ if (options.cvss) {
1007
+ const [op, val] = parseImpactFilter(options.cvss);
1008
+ filters.push((c) => {
1009
+ const score = cvssScoreOf(c);
1010
+ return score !== void 0 && compareImpact(score, op, val);
1011
+ });
1012
+ }
1013
+ if (options.epss) {
1014
+ const [op, val] = parseImpactFilter(options.epss);
1015
+ filters.push((c) => c.epss != null && compareImpact(c.epss.score, op, val));
492
1016
  }
493
- if (options.nist && options.nist.length > 0) {
494
- const nist = options.nist;
495
- filters.push((c) => nist.some((n) => tagMatchesGlob(c.tags, "nist", n)));
1017
+ if (options.kev) {
1018
+ const want = parseKevFilter(options.kev);
1019
+ filters.push((c) => want !== void 0 && inKev(c) === want);
496
1020
  }
1021
+ if (valuesActive(options.cwe)) filters.push((c) => {
1022
+ const carried = new Set((c.cwe ?? []).flatMap((raw) => extractCWEIDs(String(raw))));
1023
+ return valuesMatch(options.cwe, (want) => extractCWEIDs(want).some((id) => carried.has(id)));
1024
+ });
1025
+ if (valuesActive(options.cci)) filters.push((c) => valuesMatch(options.cci, (want) => tagContains(c.tags, "cci", want.toUpperCase())));
1026
+ if (valuesActive(options.nist)) filters.push((c) => valuesMatch(options.nist, (want) => tagMatchesGlob(c.tags, "nist", want)));
497
1027
  if (options.id) {
498
1028
  const id = options.id;
499
- filters.push((c) => tagContains(c.tags, "stig_id", id) || tagContains(c.tags, "gid", id) || tagContains(c.tags, "gtitle", id) || c.id === id);
500
- }
501
- if (options.tag && options.tag.length > 0) {
502
- const tagFilters = [];
503
- for (const t of options.tag) {
504
- const idx = t.indexOf(":");
505
- if (idx >= 0) tagFilters.push({
506
- key: t.slice(0, idx),
507
- value: t.slice(idx + 1)
508
- });
509
- }
510
- if (tagFilters.length > 0) filters.push((c) => tagFilters.some((tf) => tagMatchesGlob(c.tags, tf.key, tf.value)));
1029
+ if (/[*?]/.test(id)) filters.push((c) => tagMatchesGlob(c.tags, "stig_id", id) || tagMatchesGlob(c.tags, "gid", id) || tagMatchesGlob(c.tags, "gtitle", id) || matchesGlob(c.id, id));
1030
+ else filters.push((c) => tagContains(c.tags, "stig_id", id) || tagContains(c.tags, "gid", id) || tagContains(c.tags, "gtitle", id) || c.id === id);
511
1031
  }
1032
+ if (valuesActive(options.tag)) filters.push((c) => valuesMatch(options.tag, (want) => {
1033
+ const idx = want.indexOf(":");
1034
+ return idx > 0 && tagMatchesGlob(c.tags, want.slice(0, idx), want.slice(idx + 1));
1035
+ }));
512
1036
  if (options.search) {
513
1037
  const search = options.search.toLowerCase();
514
1038
  filters.push((c) => {
@@ -569,10 +1093,263 @@ function tagMatchesGlob(tags, key, pattern) {
569
1093
  if (Array.isArray(tagVal)) return tagVal.some((item) => typeof item === "string" && safeGlobMatch(item, pattern));
570
1094
  return false;
571
1095
  }
1096
+ /**
1097
+ * The KIND of the governing POA&M, or '' when the governing entry is an override
1098
+ * or nothing governs. Resolves through the same index governingDisposition uses,
1099
+ * so disposition and poamType can never name different entries.
1100
+ *
1101
+ * Reading the GOVERNING plan rather than any carried plan is the whole point: a
1102
+ * requirement carrying a lapsed remediation under a live mitigation is governed
1103
+ * by the mitigation, and matching it on 'remediation' would let a dead plan
1104
+ * answer for a live one.
1105
+ * Parity: governingPoamType in go/filter.go.
1106
+ */
1107
+ function governingPoamType(control, now) {
1108
+ const overrides = control.statusOverrides ?? [];
1109
+ const entries = [...overrideInputs(control), ...poamInputs(control)];
1110
+ const index = governingOverrideIndex(entries, () => true, now);
1111
+ if (index < overrides.length) return "";
1112
+ return (control.poams ?? [])[index - overrides.length]?.type ?? "";
1113
+ }
1114
+ /**
1115
+ * baselineLabelsMatch reports whether a baseline satisfies any of the
1116
+ * `key:value` label predicates. No predicates means every baseline qualifies;
1117
+ * otherwise one must match, so several values OR the way every other multi-value
1118
+ * filter does.
1119
+ *
1120
+ * A predicate without a colon is refused at the boundary by validBaselineLabel
1121
+ * rather than handled here, because selecting nothing and being ignored produce
1122
+ * the SAME false green under a max bound: the gate passes while the caller
1123
+ * believes a filter was applied. Reaching this function it selects nothing,
1124
+ * which is the safe half of that pair.
1125
+ * Parity: baselineLabelsMatch in go/filter.go.
1126
+ */
1127
+ function baselineLabelsMatch(labels, predicates) {
1128
+ if (!valuesActive(predicates)) return true;
1129
+ return valuesMatch(predicates, (p) => {
1130
+ const colon = p.indexOf(":");
1131
+ return colon > 0 && labelMatchesGlob(labels, p.slice(0, colon), p.slice(colon + 1));
1132
+ });
1133
+ }
1134
+ /**
1135
+ * labelMatchesGlob reports whether a label KEY is present and its value matches
1136
+ * the pattern. Deliberately not tagMatchesGlob: a tag value may be a list, which
1137
+ * is why that one goes through the tag helpers, while a label is exactly one
1138
+ * string by schema (`additionalProperties: {type: string}`). An absent key
1139
+ * matches nothing, including against `*` — the predicate asks about a label the
1140
+ * baseline does not carry, and there is nothing to match.
1141
+ * Parity: labelMatchesGlob in go/filter.go.
1142
+ */
1143
+ function labelMatchesGlob(labels, key, pattern) {
1144
+ const value = labels?.[key];
1145
+ if (value === void 0) return false;
1146
+ return safeGlobMatch(value, pattern);
1147
+ }
572
1148
  /** matchesGlob reports whether s matches the glob pattern (case-insensitive). */
573
1149
  function matchesGlob(s, pattern) {
574
1150
  return safeGlobMatch(s, pattern);
575
1151
  }
1152
+ /**
1153
+ * The closed vocabulary the disposition filter accepts: the schema's
1154
+ * Override_Type enum. A value outside it can only ever match nothing, which
1155
+ * would report a clean run over a filter the caller believed was applied.
1156
+ * Parity: DispositionValues in go/filter.go, pinned by the shared case table.
1157
+ * Membership is not pinned to the schema: an eighth override type would be
1158
+ * silently unfilterable in both languages until someone adds it here.
1159
+ */
1160
+ const DISPOSITION_VALUES = [
1161
+ "waiver",
1162
+ "attestation",
1163
+ "poam",
1164
+ "inherited",
1165
+ "falsePositive",
1166
+ "riskAdjustment",
1167
+ "operationalRequirement"
1168
+ ];
1169
+ /**
1170
+ * The two values the poams filter accepts. 'none-valid' covers a requirement
1171
+ * with no POA&M, with an empty list, and with only lapsed ones: a plan that has
1172
+ * expired is not a plan, and splitting the two cases would create a value whose
1173
+ * only use is to be chosen by mistake.
1174
+ */
1175
+ const POAM_VALID = "valid";
1176
+ const POAM_NONE_VALID = "none-valid";
1177
+ /**
1178
+ * Reports whether s is a POA&M validity value the filter understands. Callers
1179
+ * validate with this and reject, rather than letting an unrecognized value match
1180
+ * nothing and pass.
1181
+ */
1182
+ function validPoamFilter(s) {
1183
+ return poamFilterWantsValid(s) !== void 0;
1184
+ }
1185
+ function poamFilterWantsValid(s) {
1186
+ switch (s.trim().toLowerCase()) {
1187
+ case POAM_VALID: return true;
1188
+ case POAM_NONE_VALID: return false;
1189
+ default: return;
1190
+ }
1191
+ }
1192
+ /**
1193
+ * The type of the override that governs the requirement, or '' when none does:
1194
+ * the most recently applied non-expired override, whatever it carries. That is
1195
+ * the schema's own definition, and the rule hdf-diff has always used to compute
1196
+ * the effective checksum.
1197
+ *
1198
+ * Eligibility is deliberately unfiltered here, unlike the status and impact
1199
+ * ladders. Requiring a status — as this did — meant an override carrying only an
1200
+ * impact governed nothing, so `--disposition riskAdjustment` could not match the
1201
+ * shape a riskAdjustment normally has. The cost is that disposition may name a
1202
+ * different override than the one that decided the status, which is what
1203
+ * per-field eligibility means rather than a contradiction.
1204
+ */
1205
+ function governingDisposition(control, now) {
1206
+ const overrides = control.statusOverrides ?? [];
1207
+ const entries = [...overrideInputs(control), ...poamInputs(control)];
1208
+ const index = governingOverrideIndex(entries, () => true, now);
1209
+ if (index < 0) return "";
1210
+ if (index < overrides.length) return overrides[index]?.type ?? "";
1211
+ return "poam";
1212
+ }
1213
+ /**
1214
+ * Projects POA&Ms onto the shape the override resolver compares, carrying no
1215
+ * status or impact because a POA&M changes neither: it tracks the work being
1216
+ * done about a failure rather than adjudicating it.
1217
+ * Parity: poamInputs in go/filter.go.
1218
+ */
1219
+ function poamInputs(control) {
1220
+ return (control.poams ?? []).map((p) => ({
1221
+ appliedAt: new Date(p.appliedAt).toISOString(),
1222
+ expiresAt: new Date(p.expiresAt).toISOString()
1223
+ }));
1224
+ }
1225
+ /**
1226
+ * Whether the requirement carries a POA&M still in force. expiresAt is required
1227
+ * by the schema, so a POA&M always has a deadline to judge; one exactly at the
1228
+ * reference instant has passed, matching how an override's expiry is judged.
1229
+ */
1230
+ function hasValidPoam(control, now) {
1231
+ const parsed = now ? parseTimestamp(now) : null;
1232
+ const ref = parsed ? parsed.getTime() : Date.now();
1233
+ return (control.statusOverrides ?? []).some((o) => o.type === "poam" && new Date(o.expiresAt).getTime() > ref) || (control.poams ?? []).some((poam) => new Date(poam.expiresAt).getTime() > ref);
1234
+ }
1235
+ /**
1236
+ * The requirement's authoritative CVSS score, or undefined when it carries none.
1237
+ *
1238
+ * Two decisions live here. An entry's score is its computedScore when the
1239
+ * producer supplied one, else its baseScore: the schema calls computedScore "the
1240
+ * score consumers should treat as authoritative for risk decisions when
1241
+ * present", and converters populate it: nessus-to-hdf writes a requirement-level
1242
+ * computedScore when it has the metrics to recompute one, and hdf-to-csv already
1243
+ * resolves computedScore-else-baseScore for its own column, so a gate reading
1244
+ * baseScore alone would disagree with both. It does NOT reach
1245
+ * `hdf enrich --recompute-cvss`, which writes its recomputed score into a
1246
+ * riskAdjustment OVERRIDE's cvss block rather than the requirement's own cvss[].
1247
+ * And a
1248
+ * requirement may carry one entry per CVE, resolving to the HIGHEST of them: a
1249
+ * finding matching several CVEs is as dangerous as its worst.
1250
+ *
1251
+ * Parity: cvssScoreOf in go/filter.go.
1252
+ */
1253
+ function cvssScoreOf(control) {
1254
+ let best;
1255
+ for (const entry of control.cvss ?? []) {
1256
+ const score = entry.computedScore ?? entry.baseScore;
1257
+ if (typeof score === "number" && (best === void 0 || score > best)) best = score;
1258
+ }
1259
+ return best;
1260
+ }
1261
+ /**
1262
+ * CISA Known Exploited Vulnerabilities membership. An absent kev block reads as
1263
+ * false: a requirement nobody checked against the catalog is not
1264
+ * known-exploited, and treating absence as unknown would leave 'kev: false'
1265
+ * unable to express "everything CISA does not list".
1266
+ */
1267
+ function inKev(control) {
1268
+ return control.kev?.inKev === true;
1269
+ }
1270
+ /** Accepts only 'true' and 'false'; anything else yields undefined. */
1271
+ function parseKevFilter(s) {
1272
+ switch (s.trim().toLowerCase()) {
1273
+ case "true": return true;
1274
+ case "false": return false;
1275
+ default: return;
1276
+ }
1277
+ }
1278
+ //#endregion
1279
+ //#region src/rules.ts
1280
+ /**
1281
+ * Maps a predicate onto the engine filter. Every field is a pass-through: the
1282
+ * point of reusing the vocabulary is that there is nothing to translate, and a
1283
+ * new filter field becomes a rule field by adding it here.
1284
+ */
1285
+ function filterOptions(where, options) {
1286
+ return {
1287
+ ...where,
1288
+ now: options.now,
1289
+ count: true,
1290
+ statusOf: options.statusOf
1291
+ };
1292
+ }
1293
+ /**
1294
+ * Renders a predicate for a violation message, fields sorted so the same rule
1295
+ * always reads the same way. Values within a field join with '|', which is what
1296
+ * they mean. Parity: describe() in go/rules.go.
1297
+ */
1298
+ function describe$1(where) {
1299
+ const parts = [];
1300
+ for (const [key, value] of Object.entries(where)) {
1301
+ if (value === void 0 || value === null || value === "") continue;
1302
+ if (typeof value === "string") {
1303
+ parts.push(`${key}: ${value}`);
1304
+ continue;
1305
+ }
1306
+ if (Array.isArray(value)) {
1307
+ if (value.length > 0) parts.push(`${key}: ${value.join("|")}`);
1308
+ continue;
1309
+ }
1310
+ const v = normalizeValues(value);
1311
+ if (v.in.length > 0) parts.push(`${key}: ${v.in.join("|")}`);
1312
+ if (v.not.length > 0) parts.push(`${key}: not ${v.not.join("|")}`);
1313
+ }
1314
+ parts.sort();
1315
+ return `{${parts.join(", ")}}`;
1316
+ }
1317
+ function label(rule) {
1318
+ return rule.name && rule.name !== "" ? rule.name : `rule ${describe$1(rule.where)}`;
1319
+ }
1320
+ /**
1321
+ * Applies every rule to the document and returns one violation per breached
1322
+ * bound. Evaluation is filter → count → compare, calling the engine's own filter
1323
+ * rather than a second matcher.
1324
+ */
1325
+ function evaluateRules(config, results, options = {}) {
1326
+ const violations = [];
1327
+ for (const rule of config.rules ?? []) {
1328
+ const matches = filter(results, filterOptions(rule.where, options));
1329
+ const matched = matches.length;
1330
+ if (rule.max !== void 0 && matched > rule.max) violations.push({
1331
+ message: `${label(rule)}: ${matched} matched, maximum ${rule.max}`,
1332
+ findings: matches
1333
+ });
1334
+ if (rule.min !== void 0 && matched < rule.min) violations.push({
1335
+ message: `${label(rule)}: ${matched} matched, minimum ${rule.min}`,
1336
+ findings: matches
1337
+ });
1338
+ }
1339
+ return violations;
1340
+ }
1341
+ /**
1342
+ * Applies a whole policy — the grid and the rules — and returns every violation.
1343
+ * This is the entry point a surface should call: validateThresholds evaluates the
1344
+ * grid alone and refuses a config carrying rules, so a caller cannot
1345
+ * half-implement a policy without being told. Parity: Evaluate in go/rules.go.
1346
+ */
1347
+ function evaluate(config, input) {
1348
+ return validateGrid(config, input.counts, input.compliance, input.controlMap).concat(evaluateRules(config, input.results, {
1349
+ now: input.now,
1350
+ statusOf: input.statusOf
1351
+ }));
1352
+ }
576
1353
  //#endregion
577
1354
  //#region src/loader.ts
578
1355
  /**
@@ -778,6 +1555,6 @@ function dedupe(input) {
778
1555
  return out;
779
1556
  }
780
1557
  //#endregion
781
- export { LABEL_SOURCE_DOCUMENT, LABEL_TOOL, LABEL_TOOL_VERSION, agentOverrideCount, agentOverridesInPackage, calculateCompliance, completeness, countControlsByStatus, countControlsByStatusSeverity, coveredBaselineNames, coveredBaselinesInPackage, deriveSeverity, detect, detectFormat, engineVersion, filter, load, mapControlIDs, mapControlIDsByStatus, merge, overallStatus, parseEvidencePackage, plannedBaselineRefs, validateThresholds, verifyChecksums };
1558
+ export { LABEL_SOURCE_DOCUMENT, LABEL_TOOL, LABEL_TOOL_VERSION, SEVERITY_VALUES, STATUS_VALUES, addCounts, advertisedFilterValues, agentOverrideCount, agentOverridesInPackage, calculateCompliance, completeness, countControlsByStatus, countControlsByStatusSeverity, coveredBaselineNames, coveredBaselinesInPackage, deriveSeverity, detect, detectFormat, effectiveImpactOf, engineVersion, evaluate, evaluateRules, filter, filterAliases, filterValues, load, mapControlIDs, mapControlIDsByStatus, merge, normalizeFilterValue, normalizeKey, normalizeThresholdConfig, overallStatus, overrideInputs, parseEvidencePackage, plannedBaselineRefs, ruleRefusal, severityBucket, severityTotals, validSeverity, validStatus, validateGrid, validateThresholds, verifyChecksums, violationMessages };
782
1559
 
783
1560
  //# sourceMappingURL=index.js.map