@mitre/hdf-engine 3.6.0 → 3.7.0-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/README.md +172 -3
- package/dist/index.d.ts +72 -28
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +168 -14
- package/dist/index.js.map +1 -1
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -1,7 +1,176 @@
|
|
|
1
1
|
# @mitre/hdf-engine
|
|
2
2
|
|
|
3
|
-
Shared, schema-typed read-side engines for Heimdall Data Format (HDF) documents — document-type **detection**, requirement **query/filtering**,
|
|
3
|
+
Shared, schema-typed read-side engines for Heimdall Data Format (HDF) documents — document-type **detection**, requirement **query/filtering**, **compliance** rollups and threshold verdicts, the document **loader**, the **evidence-verify** core, and multi-document **merge**.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## Why this exists
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Reading an HDF document correctly is harder than it looks. Deciding a requirement's effective status means resolving amendments and impact-zero rules; counting by severity means agreeing on what an absent severity derives to; detecting a document's type means fingerprinting keys that several types share. Each of those has exactly one right answer, and every consumer that reimplements it drifts from the others.
|
|
8
|
+
|
|
9
|
+
So the engines live here rather than in any one consumer. The `hdf` CLI and the HDF MCP server both delegate to this package, which is why they cannot disagree about the same document. It sits above `@mitre/hdf-schema` (types) and `@mitre/hdf-utilities` (schema-free primitives), and is a sibling to `@mitre/hdf-diff`, which owns diff, change events and amend.
|
|
10
|
+
|
|
11
|
+
Dual-language and kept at parity: TypeScript (`@mitre/hdf-engine`) and Go (`github.com/mitre/hdf-libs/hdf-engine/go/v3`).
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @mitre/hdf-engine
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
go get github.com/mitre/hdf-libs/hdf-engine/go/v3
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
### Detect a document's type
|
|
26
|
+
|
|
27
|
+
Returns the HDF document type, or an empty result when the bytes are not an HDF document:
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { detect } from '@mitre/hdf-engine';
|
|
31
|
+
|
|
32
|
+
const docType = detect(bytes); // 'results' | 'baseline' | 'system' | ...
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```go
|
|
36
|
+
import hdfengine "github.com/mitre/hdf-libs/hdf-engine/go/v3"
|
|
37
|
+
|
|
38
|
+
docType := hdfengine.Detect(data) // "" when not an HDF document
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Query requirements
|
|
42
|
+
|
|
43
|
+
Filter a results document by status, severity, impact, control identifiers, tags or free text. Filters combine with AND; the values within one filter combine with OR:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { filter } from '@mitre/hdf-engine';
|
|
47
|
+
|
|
48
|
+
const matches = filter(results, {
|
|
49
|
+
status: ['failed'],
|
|
50
|
+
severity: ['critical', 'high'],
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```go
|
|
55
|
+
matches := hdfengine.Filter(ctx, results, hdfengine.Options{
|
|
56
|
+
Status: []string{"failed"},
|
|
57
|
+
Severity: []string{"critical", "high"},
|
|
58
|
+
})
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`Tag` matches `key=value` and accepts globs, which is how source-specific data reaches a query without this package knowing the vocabulary of every scanner.
|
|
62
|
+
|
|
63
|
+
### Roll up compliance
|
|
64
|
+
|
|
65
|
+
Counts are sliced by status and, within each status, by severity:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { countControlsByStatusSeverity, calculateCompliance } from '@mitre/hdf-engine';
|
|
69
|
+
|
|
70
|
+
const counts = countControlsByStatusSeverity(results);
|
|
71
|
+
const pct = calculateCompliance(counts); // passed / (passed+failed+skipped+error) * 100
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
```go
|
|
75
|
+
counts := hdfengine.CountControlsByStatusSeverity(results)
|
|
76
|
+
pct := hdfengine.CalculateCompliance(counts)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`notApplicable` is excluded from the denominator: a requirement that does not apply is not evidence of compliance either way.
|
|
80
|
+
|
|
81
|
+
### Apply a threshold
|
|
82
|
+
|
|
83
|
+
A threshold is a policy of bounds over those counts. `validateThresholds` returns one message per breached bound, and an empty list when the document passes:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { validateThresholds } from '@mitre/hdf-engine';
|
|
87
|
+
|
|
88
|
+
const violations = validateThresholds(config, counts, pct, controlMap);
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
```go
|
|
92
|
+
violations := hdfengine.ValidateThresholds(config, counts, pct, controlMap)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
See the [thresholds guide](https://mitre.github.io/hdf-libs/docs/guides/thresholds-workflow) for the file format and how a pipeline gates on it.
|
|
96
|
+
|
|
97
|
+
### Merge several scans into one view
|
|
98
|
+
|
|
99
|
+
Combine several results documents into one multi-baseline document — one baseline
|
|
100
|
+
per input baseline, renamed `<tool>/<original>`, with each input's provenance kept
|
|
101
|
+
verbatim. The semantics are a union: no requirement is deduplicated, re-keyed or
|
|
102
|
+
dropped, and the same inputs in the same order always produce the same output.
|
|
103
|
+
|
|
104
|
+
```go
|
|
105
|
+
merged, warnings, err := hdfengine.Merge([]hdfengine.MergeSource{
|
|
106
|
+
{Name: "nessus-scan", Doc: nessusResults},
|
|
107
|
+
{Name: "checkov-scan", Doc: checkovResults},
|
|
108
|
+
})
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
The warnings report what the merge could not carry cleanly; they are advisory
|
|
112
|
+
rather than failures, so check them rather than assuming a clean pass.
|
|
113
|
+
|
|
114
|
+
Because `tool` and `generator` are document-root fields, a merged view cannot say
|
|
115
|
+
per baseline which scanner produced it — so the merge writes that provenance onto
|
|
116
|
+
each baseline's labels instead.
|
|
117
|
+
|
|
118
|
+
### Verify an evidence package
|
|
119
|
+
|
|
120
|
+
Parse a package, check the checksums of everything it references, and report whether the plan's baselines are covered:
|
|
121
|
+
|
|
122
|
+
```go
|
|
123
|
+
name, contents, err := hdfengine.ParseEvidencePackage(pkg)
|
|
124
|
+
results := hdfengine.VerifyChecksums(contents, fetch)
|
|
125
|
+
report := hdfengine.Completeness(planned, covered)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The `fetch` function is supplied by the caller, so this package never reads the filesystem or the network itself.
|
|
129
|
+
|
|
130
|
+
## API
|
|
131
|
+
|
|
132
|
+
### Detection
|
|
133
|
+
|
|
134
|
+
- `detect(data)` / `Detect(data)` — the document's type, empty when not HDF
|
|
135
|
+
- `KnownTypes()` (Go) — every type detection can return
|
|
136
|
+
|
|
137
|
+
### Query
|
|
138
|
+
|
|
139
|
+
- `filter(results, options)` / `Filter(ctx, results, opts)` — matching requirements
|
|
140
|
+
- `FilterOptions` / `Options` — `status`, `severity`, `impact`, `cci`, `nist`, `id`, `tag`, `search`, `baseline`, `limit`, `count`, and a `statusOf` hook to override how status is resolved
|
|
141
|
+
- `Match` — one result row
|
|
142
|
+
|
|
143
|
+
### Compliance
|
|
144
|
+
|
|
145
|
+
- `countControlsByStatusSeverity` / `CountControlsByStatusSeverity` — counts by status and severity
|
|
146
|
+
- `countControlsByStatus` / `CountControlsByStatus` — counts with a caller-supplied status resolver
|
|
147
|
+
- `calculateCompliance` / `CalculateCompliance` — the percentage
|
|
148
|
+
- `deriveSeverity` / `DeriveSeverity` — a requirement's severity, explicit or derived from impact
|
|
149
|
+
- `overallStatus` (TypeScript only) — the worst status across a requirement's results; the Go peer is internal to the package
|
|
150
|
+
- `mapControlIDs`, `mapControlIDsByStatus` / `MapControlIDs`, `MapControlIDsByStatus` — control id to status/severity
|
|
151
|
+
- `agentOverrideCount` / `AgentOverrideCount` — overrides attributed to an agent
|
|
152
|
+
- `validateThresholds` / `ValidateThresholds` — threshold verdicts
|
|
153
|
+
- `StatusCounts`, `SeverityCounts`, `ControlIDMapping`, `ThresholdConfig`, `ThresholdSeverity`, `ThresholdBound`, `ComplianceBound`
|
|
154
|
+
|
|
155
|
+
### Merge
|
|
156
|
+
|
|
157
|
+
- `merge` / `Merge` — combine results documents into one multi-baseline view; the Go form returns the document, warnings and an error, the TypeScript form a `MergeResult`
|
|
158
|
+
- `MergeSource` — one input: a results document plus the name it is recorded under
|
|
159
|
+
|
|
160
|
+
### Loader
|
|
161
|
+
|
|
162
|
+
- `load(data, maxSize)` / `Load(data, maxSize)` — parse and normalize input
|
|
163
|
+
- `detectFormat` (TypeScript only) — the detected input shape; `InputFormat` and `LoadResult` are the accompanying types
|
|
164
|
+
|
|
165
|
+
### Evidence
|
|
166
|
+
|
|
167
|
+
- `parseEvidencePackage` / `ParseEvidencePackage` — package name and contents
|
|
168
|
+
- `verifyChecksums` / `VerifyChecksums` — per-reference checksum status
|
|
169
|
+
- `plannedBaselineRefs`, `coveredBaselineNames`, `coveredBaselinesInPackage` — plan coverage inputs
|
|
170
|
+
- `agentOverridesInPackage` / `AgentOverridesInPackage` — agent-attributed overrides across a package
|
|
171
|
+
- `completeness` / `Completeness` — planned versus covered
|
|
172
|
+
- `ChecksumStatus`, `EvidenceContent`, `ChecksumResult`, `CompletenessResult`, `FetchFn` / `FetchFunc`
|
|
173
|
+
|
|
174
|
+
### Version
|
|
175
|
+
|
|
176
|
+
- `engineVersion` (TS) / `Version()` (Go) — the package version, used to stamp generated documents
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,39 @@
|
|
|
1
1
|
import { EvaluatedRequirement, HDFBaseline, HDFResults, RequirementResult, Severity } from "@mitre/hdf-schema";
|
|
2
|
+
//#region src/version.d.ts
|
|
3
|
+
export declare const engineVersion = "3.7.0";
|
|
4
|
+
//#endregion
|
|
5
|
+
//#region src/merge.d.ts
|
|
6
|
+
/** One input to merge: a results document and the name it is recorded under. */
|
|
7
|
+
interface MergeSource {
|
|
8
|
+
name: string;
|
|
9
|
+
doc: HDFResults;
|
|
10
|
+
}
|
|
11
|
+
type MergeWarningKind = 'duplicate-baseline-name' | 'label-overwritten';
|
|
12
|
+
/** A non-fatal condition merge reports rather than silently resolving. */
|
|
13
|
+
interface MergeWarning {
|
|
14
|
+
kind: MergeWarningKind;
|
|
15
|
+
/** Merged baseline name. */
|
|
16
|
+
name: string;
|
|
17
|
+
/** Merged baseline positions. */
|
|
18
|
+
indices: number[];
|
|
19
|
+
/** Set for label warnings only: the label key that was replaced or removed. */
|
|
20
|
+
label?: string;
|
|
21
|
+
}
|
|
22
|
+
interface MergeResult {
|
|
23
|
+
results: HDFResults;
|
|
24
|
+
warnings: MergeWarning[];
|
|
25
|
+
}
|
|
26
|
+
/** Provenance label keys written on every merged baseline (ADR-0016 §3). */
|
|
27
|
+
export declare const LABEL_TOOL = "tool";
|
|
28
|
+
export declare const LABEL_TOOL_VERSION = "toolVersion";
|
|
29
|
+
export declare const LABEL_SOURCE_DOCUMENT = "sourceDocument";
|
|
30
|
+
/**
|
|
31
|
+
* merge combines the sources, in order, into one results document. Returns the
|
|
32
|
+
* document and any warnings (a collision or overwrite is never an error);
|
|
33
|
+
* throws only when there is nothing to merge. Inputs are not mutated.
|
|
34
|
+
*/
|
|
35
|
+
export declare function merge(sources: MergeSource[]): MergeResult;
|
|
36
|
+
//#endregion
|
|
2
37
|
//#region src/detect.d.ts
|
|
3
38
|
/** The eight HDF document type strings, matching validators.Type* in Go. */
|
|
4
39
|
type HdfDocType = 'results' | 'baseline' | 'system' | 'plan' | 'amendments' | 'evidence-package' | 'comparison' | 'requirement-change-event' | '';
|
|
@@ -7,7 +42,7 @@ type HdfDocType = 'results' | 'baseline' | 'system' | 'plan' | 'amendments' | 'e
|
|
|
7
42
|
* type string, or '' when the input is not a JSON object or matches no known
|
|
8
43
|
* HDF document type.
|
|
9
44
|
*/
|
|
10
|
-
declare function detect(input: string): HdfDocType;
|
|
45
|
+
export declare function detect(input: string): HdfDocType;
|
|
11
46
|
//#endregion
|
|
12
47
|
//#region src/query.d.ts
|
|
13
48
|
/**
|
|
@@ -30,7 +65,13 @@ interface FilterOptions {
|
|
|
30
65
|
count?: boolean;
|
|
31
66
|
statusOf?: (control: EvaluatedRequirement) => string;
|
|
32
67
|
}
|
|
33
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
* A single query result row. baselineIndex and index are the match's position in
|
|
70
|
+
* the result set (results.baselines[baselineIndex].requirements[index]) and are
|
|
71
|
+
* the only unique identity a match has: baseline names repeat in shipped
|
|
72
|
+
* converter output and requirement ids repeat within a baseline, so (baseline,
|
|
73
|
+
* id) is not a key. Address the source requirement by position, never by name.
|
|
74
|
+
*/
|
|
34
75
|
interface Match {
|
|
35
76
|
id: string;
|
|
36
77
|
title: string;
|
|
@@ -38,13 +79,15 @@ interface Match {
|
|
|
38
79
|
impact: number;
|
|
39
80
|
severity: string;
|
|
40
81
|
baseline: string;
|
|
82
|
+
baselineIndex: number;
|
|
83
|
+
index: number;
|
|
41
84
|
}
|
|
42
85
|
/**
|
|
43
86
|
* filter returns the requirements across the result set's baselines that satisfy
|
|
44
87
|
* options. Applies to requirement collections (results/baseline documents); the
|
|
45
88
|
* calling adapter rejects document types that carry no requirements.
|
|
46
89
|
*/
|
|
47
|
-
declare function filter(results: HDFResults, options: FilterOptions): Match[];
|
|
90
|
+
export declare function filter(results: HDFResults, options: FilterOptions): Match[];
|
|
48
91
|
//#endregion
|
|
49
92
|
//#region src/loader.d.ts
|
|
50
93
|
/** Wire encoding of loader input (parity with Go InputFormat). */
|
|
@@ -65,14 +108,14 @@ interface LoadResult {
|
|
|
65
108
|
* hdf-parsers parse for the results and baseline types. Other types are
|
|
66
109
|
* detected but not parsed here.
|
|
67
110
|
*/
|
|
68
|
-
declare function load(input: string | Uint8Array, maxSize?: number): LoadResult;
|
|
111
|
+
export declare function load(input: string | Uint8Array, maxSize?: number): LoadResult;
|
|
69
112
|
/**
|
|
70
113
|
* detectFormat classifies input as a single JSON document or newline-delimited
|
|
71
114
|
* JSON, consistent with the Go core: NDJSON is two or more non-blank lines that
|
|
72
115
|
* each independently parse as a complete JSON value. A pretty-printed single
|
|
73
116
|
* object stays 'json' (its first line is not itself a complete JSON value).
|
|
74
117
|
*/
|
|
75
|
-
declare function detectFormat(text: string): InputFormat;
|
|
118
|
+
export declare function detectFormat(text: string): InputFormat;
|
|
76
119
|
//#endregion
|
|
77
120
|
//#region src/evidence.d.ts
|
|
78
121
|
/** Classifies a single content entry's checksum verification. */
|
|
@@ -105,31 +148,31 @@ interface CompletenessResult {
|
|
|
105
148
|
* uri cannot be read. */
|
|
106
149
|
type FetchFn = (uri: string) => Uint8Array;
|
|
107
150
|
/** Extracts the planRef and content entries from an evidence-package document. */
|
|
108
|
-
declare function parseEvidencePackage(pkg: string): {
|
|
151
|
+
export declare function parseEvidencePackage(pkg: string): {
|
|
109
152
|
planRef: string;
|
|
110
153
|
contents: EvidenceContent[];
|
|
111
154
|
};
|
|
112
155
|
/** Verifies each content entry's sha256 against fetch(uri), preserving entry
|
|
113
156
|
* order. No checksum → skipped; a fetch throw → error; hash mismatch → mismatch
|
|
114
157
|
* (carrying expected+actual). */
|
|
115
|
-
declare function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): ChecksumResult[];
|
|
158
|
+
export declare function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): ChecksumResult[];
|
|
116
159
|
/** Extracts assessment baselineRefs from a plan document, deduped in first-seen
|
|
117
160
|
* order. */
|
|
118
|
-
declare function plannedBaselineRefs(plan: string): string[];
|
|
161
|
+
export declare function plannedBaselineRefs(plan: string): string[];
|
|
119
162
|
/** Extracts baseline names from a results document, deduped in first-seen order. */
|
|
120
|
-
declare function coveredBaselineNames(results: string): string[];
|
|
163
|
+
export declare function coveredBaselineNames(results: string): string[];
|
|
121
164
|
/** Concatenates the covered baseline names of every hdf-results document the
|
|
122
165
|
* package references, in entry order. An entry that cannot be fetched or parsed
|
|
123
166
|
* is skipped: checksum verification is what reports a read failure, and a
|
|
124
167
|
* partial coverage list is what the completeness diff needs. */
|
|
125
|
-
declare function coveredBaselinesInPackage(contents: EvidenceContent[], fetch: FetchFn): string[];
|
|
168
|
+
export declare function coveredBaselinesInPackage(contents: EvidenceContent[], fetch: FetchFn): string[];
|
|
126
169
|
/** Sums the agent-attributed override count across every hdf-results document
|
|
127
170
|
* the package references. Unreadable or unparseable entries are skipped. */
|
|
128
|
-
declare function agentOverridesInPackage(contents: EvidenceContent[], fetch: FetchFn): number;
|
|
171
|
+
export declare function agentOverridesInPackage(contents: EvidenceContent[], fetch: FetchFn): number;
|
|
129
172
|
/** Diffs planned baseline refs against covered baseline names. A planned ref is
|
|
130
173
|
* covered when some results baseline shares its name. Missing is sorted so the
|
|
131
174
|
* outcome is deterministic across languages and runs. */
|
|
132
|
-
declare function completeness(planned: string[], covered: string[]): CompletenessResult;
|
|
175
|
+
export declare function completeness(planned: string[], covered: string[]): CompletenessResult;
|
|
133
176
|
//#endregion
|
|
134
177
|
//#region src/compliance.d.ts
|
|
135
178
|
interface SeverityCounts {
|
|
@@ -137,7 +180,8 @@ interface SeverityCounts {
|
|
|
137
180
|
high: number;
|
|
138
181
|
medium: number;
|
|
139
182
|
low: number;
|
|
140
|
-
|
|
183
|
+
/** The schema's fifth severity; also absorbs a severity that cannot be derived or is not in the enum. */
|
|
184
|
+
informational: number;
|
|
141
185
|
total: number;
|
|
142
186
|
}
|
|
143
187
|
interface StatusCounts {
|
|
@@ -162,6 +206,8 @@ interface ThresholdSeverity {
|
|
|
162
206
|
high?: ThresholdBound;
|
|
163
207
|
medium?: ThresholdBound;
|
|
164
208
|
low?: ThresholdBound;
|
|
209
|
+
informational?: ThresholdBound;
|
|
210
|
+
/** Pre-3.7 spelling of `informational`, normalized on read and never written. */
|
|
165
211
|
none?: ThresholdBound;
|
|
166
212
|
total?: ThresholdBound;
|
|
167
213
|
}
|
|
@@ -183,14 +229,16 @@ interface ThresholdConfig {
|
|
|
183
229
|
* passed > notApplicable > notReviewed; empty → notReviewed). No local rank
|
|
184
230
|
* switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).
|
|
185
231
|
*/
|
|
186
|
-
declare function overallStatus(results: RequirementResult[]): string;
|
|
232
|
+
export declare function overallStatus(results: RequirementResult[]): string;
|
|
187
233
|
/**
|
|
188
234
|
* deriveSeverity determines the severity string from impact and optional explicit
|
|
189
|
-
* severity, using impactToSeverity.
|
|
235
|
+
* severity, using impactToSeverity. Both paths yield a value from the schema's
|
|
236
|
+
* severity enum: an explicit informational and an impact-derived one are the same
|
|
237
|
+
* thing and must not land in different buckets.
|
|
190
238
|
*/
|
|
191
|
-
declare function deriveSeverity(impact: number, severity?: Severity | null): string;
|
|
239
|
+
export declare function deriveSeverity(impact: number, severity?: Severity | null): string;
|
|
192
240
|
/** CountControlsByStatusSeverity counts requirements by overall status and severity. */
|
|
193
|
-
declare function countControlsByStatusSeverity(results: HDFResults): StatusCounts;
|
|
241
|
+
export declare function countControlsByStatusSeverity(results: HDFResults): StatusCounts;
|
|
194
242
|
/**
|
|
195
243
|
* countControlsByStatus counts requirements by a caller-resolved status — the
|
|
196
244
|
* injected-resolver twin of countControlsByStatusSeverity (which counts raw
|
|
@@ -201,16 +249,16 @@ declare function countControlsByStatusSeverity(results: HDFResults): StatusCount
|
|
|
201
249
|
* (e.g. compliance with and without agent-attributed overrides) without the
|
|
202
250
|
* engine binding to any one status convention. Parity: go/compliance.go.
|
|
203
251
|
*/
|
|
204
|
-
declare function countControlsByStatus(results: HDFResults, statusOf?: (req: EvaluatedRequirement) => string): StatusCounts;
|
|
252
|
+
export declare function countControlsByStatus(results: HDFResults, statusOf?: (req: EvaluatedRequirement) => string): StatusCounts;
|
|
205
253
|
/**
|
|
206
254
|
* agentOverrideCount counts the status overrides across a result set whose
|
|
207
255
|
* applied-by identity type is "agent" — the detective count. Deterministic
|
|
208
256
|
* from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny
|
|
209
257
|
* signal. Parity: go/compliance.go AgentOverrideCount.
|
|
210
258
|
*/
|
|
211
|
-
declare function agentOverrideCount(results: HDFResults): number;
|
|
259
|
+
export declare function agentOverrideCount(results: HDFResults): number;
|
|
212
260
|
/** MapControlIDs builds control ID → status/severity mappings from a result set. */
|
|
213
|
-
declare function mapControlIDs(results: HDFResults): ControlIDMapping[];
|
|
261
|
+
export declare function mapControlIDs(results: HDFResults): ControlIDMapping[];
|
|
214
262
|
/**
|
|
215
263
|
* mapControlIDsByStatus builds control ID → status/severity mappings using a
|
|
216
264
|
* caller-resolved status — the injected-resolver twin of mapControlIDs (which
|
|
@@ -220,21 +268,17 @@ declare function mapControlIDs(results: HDFResults): ControlIDMapping[];
|
|
|
220
268
|
* listings (the same injection pattern as countControlsByStatus). Parity:
|
|
221
269
|
* go/compliance.go MapControlIDsByStatus.
|
|
222
270
|
*/
|
|
223
|
-
declare function mapControlIDsByStatus(results: HDFResults, statusOf?: (req: EvaluatedRequirement) => string): ControlIDMapping[];
|
|
271
|
+
export declare function mapControlIDsByStatus(results: HDFResults, statusOf?: (req: EvaluatedRequirement) => string): ControlIDMapping[];
|
|
224
272
|
/**
|
|
225
273
|
* calculateCompliance returns the compliance percentage rounded to two decimals:
|
|
226
274
|
* passed / (passed + failed + skipped + error) * 100; notApplicable excluded.
|
|
227
275
|
*/
|
|
228
|
-
declare function calculateCompliance(counts: StatusCounts): number;
|
|
276
|
+
export declare function calculateCompliance(counts: StatusCounts): number;
|
|
229
277
|
/**
|
|
230
278
|
* validateThresholds checks all threshold bounds against observed counts and
|
|
231
279
|
* compliance, returning human-readable violation messages (empty when all pass).
|
|
232
280
|
*/
|
|
233
|
-
declare function validateThresholds(config: ThresholdConfig, counts: StatusCounts, compliance: number, controlMap: ControlIDMapping[]): string[];
|
|
234
|
-
//#endregion
|
|
235
|
-
//#region src/index.d.ts
|
|
236
|
-
/** Library version, kept on the workspace lockstep. */
|
|
237
|
-
declare const engineVersion = "3.6.0";
|
|
281
|
+
export declare function validateThresholds(config: ThresholdConfig, counts: StatusCounts, compliance: number, controlMap: ControlIDMapping[]): string[];
|
|
238
282
|
//#endregion
|
|
239
|
-
export {
|
|
283
|
+
export type { ChecksumResult, ChecksumStatus, CompletenessResult, ComplianceBound, ControlIDMapping, EvidenceContent, FetchFn, FilterOptions, HdfDocType, InputFormat, LoadResult, Match, MergeResult, MergeSource, MergeWarning, MergeWarningKind, SeverityCounts, StatusCounts, ThresholdBound, ThresholdConfig, ThresholdSeverity };
|
|
240
284
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/version.ts","../src/merge.ts","../src/detect.ts","../src/query.ts","../src/loader.ts","../src/evidence.ts","../src/compliance.ts"],"mappings":";;qBAIa;;;;UCQI;EACf;EACA,KAAK;;KAGK;;UAGK;EACf,MAAM;;EAEN;;EAEA;;EAEA;;UAGe;EACf,SAAS;EACT,UAAU;;;qBAIC;qBACA;qBACA;;;;;;wBAUG,MAAM,SAAS,gBAAgB;;;;KCzCnC;;;;;;wBAgBI,OAAO,gBAAgB;;;;;;;;;UCRtB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,YAAY,SAAS;;;;;;;;;UAUN;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;wBAUc,OAAO,SAAS,YAAY,SAAS,gBAAgB;;;;KC1CzD;UAEK;EACf,QAAQ;EACR,SAAS;EACT,UAAU;EACV,WAAW;;EAEX;EACA;;;;;;;;;wBAUc,KAAK,gBAAgB,YAAY,mBAAc;;;;;;;wBAqC/C,aAAa,eAAe;;;;KCzDhC;;;UAIK;EACf;EACA;EACA;;;UAIe;EACf;EACA;EACA,QAAQ;EACR;EACA;EACA;;;UAIe;EACf;EACA;EACA;EACA;;;;;KAMU,WAAW,gBAAgB;;wBAuCvB,qBAAqB;EAAgB;EAAiB,UAAU;;;;;wBAgBhE,gBAAgB,UAAU,mBAAmB,OAAO,UAAU;;;wBAsB9D,oBAAoB;;wBASpB,qBAAqB;;;;;wBAYrB,0BAA0B,UAAU,mBAAmB,OAAO;;;wBAc9D,wBAAwB,UAAU,mBAAmB,OAAO;;;;wBAoC5D,aAAa,mBAAmB,oBAAoB;;;UChLnD;EACf;EACA;EACA;EACA;;EAEA;EACA;;UAGe;EACf,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,UAAU;;UAGK;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf,WAAW;EACX,OAAO;EACP,SAAS;EACT,MAAM;EACN,gBAAgB;;EAEhB,OAAO;EACP,QAAQ;;UAGO;EACf;EACA;;UAGe;EACf,aAAa;EACb,SAAS;EACT,SAAS;EACT,UAAU;EACV,QAAQ;EACR,WAAW;;;;;;;;wBAuBG,cAAc,SAAS;;;;;;;wBAUvB,eAAe,gBAAgB,WAAW;;wBAqE1C,8BAA8B,SAAS,aAAa;;;;;;;;;;;wBAoBpD,sBACd,SAAS,YACT,YAAY,KAAK,kCAChB;;;;;;;wBAiBa,mBAAmB,SAAS;;wBAe5B,cAAc,SAAS,aAAa;;;;;;;;;;wBAwBpC,sBACd,SAAS,YACT,YAAY,KAAK,kCAChB;;;;;wBAuBa,oBAAoB,QAAQ;;;;;wBAyC5B,mBACd,QAAQ,iBACR,QAAQ,cACR,oBACA,YAAY"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,135 @@
|
|
|
1
1
|
import { impactToSeverity, validateInputSize, worstStatus } from "@mitre/hdf-utilities";
|
|
2
2
|
import { parseBaseline, parseResults } from "@mitre/hdf-parsers";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
|
+
//#region src/version.ts
|
|
5
|
+
const engineVersion = "3.7.0";
|
|
6
|
+
//#endregion
|
|
7
|
+
//#region src/merge.ts
|
|
8
|
+
/** Provenance label keys written on every merged baseline (ADR-0016 §3). */
|
|
9
|
+
const LABEL_TOOL = "tool";
|
|
10
|
+
const LABEL_TOOL_VERSION = "toolVersion";
|
|
11
|
+
const LABEL_SOURCE_DOCUMENT = "sourceDocument";
|
|
12
|
+
const MERGE_GENERATOR_NAME = "hdf-merge";
|
|
13
|
+
const MERGE_EXTENSION_KEY = "hdf-merge";
|
|
14
|
+
/**
|
|
15
|
+
* merge combines the sources, in order, into one results document. Returns the
|
|
16
|
+
* document and any warnings (a collision or overwrite is never an error);
|
|
17
|
+
* throws only when there is nothing to merge. Inputs are not mutated.
|
|
18
|
+
*/
|
|
19
|
+
function merge(sources) {
|
|
20
|
+
if (sources.length === 0) throw new Error("merge: no sources");
|
|
21
|
+
const baselines = [];
|
|
22
|
+
const components = [];
|
|
23
|
+
const warnings = [];
|
|
24
|
+
const seenComponent = /* @__PURE__ */ new Set();
|
|
25
|
+
const provenance = [];
|
|
26
|
+
const positionsByName = /* @__PURE__ */ new Map();
|
|
27
|
+
let latest;
|
|
28
|
+
sources.forEach((src, index) => {
|
|
29
|
+
const prefix = toolPrefix(src.doc, index);
|
|
30
|
+
const version = toolVersion(src.doc);
|
|
31
|
+
for (const b of src.doc.baselines ?? []) {
|
|
32
|
+
const name = `${prefix}/${b.name}`;
|
|
33
|
+
const pos = baselines.length;
|
|
34
|
+
const labels = { ...b.labels ?? {} };
|
|
35
|
+
setLabel(warnings, labels, LABEL_TOOL, prefix, name, pos);
|
|
36
|
+
if (version !== "") setLabel(warnings, labels, LABEL_TOOL_VERSION, version, name, pos);
|
|
37
|
+
else if ("toolVersion" in labels) {
|
|
38
|
+
delete labels[LABEL_TOOL_VERSION];
|
|
39
|
+
warnings.push({
|
|
40
|
+
kind: "label-overwritten",
|
|
41
|
+
name,
|
|
42
|
+
indices: [pos],
|
|
43
|
+
label: LABEL_TOOL_VERSION
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
setLabel(warnings, labels, LABEL_SOURCE_DOCUMENT, src.name, name, pos);
|
|
47
|
+
const positions = positionsByName.get(name);
|
|
48
|
+
if (positions) positions.push(pos);
|
|
49
|
+
else positionsByName.set(name, [pos]);
|
|
50
|
+
baselines.push({
|
|
51
|
+
...b,
|
|
52
|
+
name,
|
|
53
|
+
labels
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
for (const c of src.doc.components ?? []) {
|
|
57
|
+
if (c.componentId !== void 0) {
|
|
58
|
+
if (seenComponent.has(c.componentId)) continue;
|
|
59
|
+
seenComponent.add(c.componentId);
|
|
60
|
+
}
|
|
61
|
+
components.push(c);
|
|
62
|
+
}
|
|
63
|
+
if (src.doc.timestamp !== void 0 && (latest === void 0 || millis(src.doc.timestamp) > millis(latest))) latest = src.doc.timestamp;
|
|
64
|
+
provenance.push(sourceProvenance(index, src));
|
|
65
|
+
});
|
|
66
|
+
for (const [name, positions] of positionsByName) if (positions.length > 1) warnings.push({
|
|
67
|
+
kind: "duplicate-baseline-name",
|
|
68
|
+
name,
|
|
69
|
+
indices: positions
|
|
70
|
+
});
|
|
71
|
+
return {
|
|
72
|
+
results: {
|
|
73
|
+
baselines,
|
|
74
|
+
...components.length > 0 ? { components } : {},
|
|
75
|
+
extensions: { [MERGE_EXTENSION_KEY]: {
|
|
76
|
+
version: engineVersion,
|
|
77
|
+
sources: provenance
|
|
78
|
+
} },
|
|
79
|
+
generator: {
|
|
80
|
+
name: MERGE_GENERATOR_NAME,
|
|
81
|
+
version: engineVersion
|
|
82
|
+
},
|
|
83
|
+
...latest !== void 0 ? { timestamp: latest } : {}
|
|
84
|
+
},
|
|
85
|
+
warnings
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function setLabel(warnings, labels, key, value, name, pos) {
|
|
89
|
+
if (key in labels) warnings.push({
|
|
90
|
+
kind: "label-overwritten",
|
|
91
|
+
name,
|
|
92
|
+
indices: [pos],
|
|
93
|
+
label: key
|
|
94
|
+
});
|
|
95
|
+
labels[key] = value;
|
|
96
|
+
}
|
|
97
|
+
/** `<tool>` of a merged baseline name: tool.name → generator.name → doc<N>, lower-cased and trimmed. */
|
|
98
|
+
function toolPrefix(doc, index) {
|
|
99
|
+
const tool = normalizeName(doc.tool?.name);
|
|
100
|
+
if (tool !== "") return tool;
|
|
101
|
+
const generator = normalizeName(doc.generator?.name);
|
|
102
|
+
if (generator !== "") return generator;
|
|
103
|
+
return `doc${index}`;
|
|
104
|
+
}
|
|
105
|
+
function normalizeName(s) {
|
|
106
|
+
return (s ?? "").trim().toLowerCase();
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* millis reads a document timestamp for comparison. The schema type is Date,
|
|
110
|
+
* but a document parsed from JSON carries the RFC 3339 string verbatim (the
|
|
111
|
+
* loader does not revive dates), so both are accepted; the value itself is
|
|
112
|
+
* carried through unchanged so output stays byte-faithful to the input.
|
|
113
|
+
*/
|
|
114
|
+
function millis(ts) {
|
|
115
|
+
return ts instanceof Date ? ts.getTime() : Date.parse(ts);
|
|
116
|
+
}
|
|
117
|
+
function toolVersion(doc) {
|
|
118
|
+
return (doc.tool?.version ?? "").trim();
|
|
119
|
+
}
|
|
120
|
+
/** One input's root metadata, verbatim, for extensions["hdf-merge"].sources[]. */
|
|
121
|
+
function sourceProvenance(index, src) {
|
|
122
|
+
const entry = {
|
|
123
|
+
index,
|
|
124
|
+
name: src.name
|
|
125
|
+
};
|
|
126
|
+
if (src.doc.tool !== void 0) entry.tool = src.doc.tool;
|
|
127
|
+
if (src.doc.generator !== void 0) entry.generator = src.doc.generator;
|
|
128
|
+
if (src.doc.timestamp !== void 0) entry.timestamp = src.doc.timestamp;
|
|
129
|
+
if (src.doc.runner !== void 0) entry.runner = src.doc.runner;
|
|
130
|
+
return entry;
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
4
133
|
//#region src/detect.ts
|
|
5
134
|
/**
|
|
6
135
|
* Detect fingerprints an HDF document by its root keys and returns the schema
|
|
@@ -41,7 +170,7 @@ function newSeverityCounts() {
|
|
|
41
170
|
high: 0,
|
|
42
171
|
medium: 0,
|
|
43
172
|
low: 0,
|
|
44
|
-
|
|
173
|
+
informational: 0,
|
|
45
174
|
total: 0
|
|
46
175
|
};
|
|
47
176
|
}
|
|
@@ -65,12 +194,13 @@ function overallStatus(results) {
|
|
|
65
194
|
}
|
|
66
195
|
/**
|
|
67
196
|
* deriveSeverity determines the severity string from impact and optional explicit
|
|
68
|
-
* severity, using impactToSeverity.
|
|
197
|
+
* severity, using impactToSeverity. Both paths yield a value from the schema's
|
|
198
|
+
* severity enum: an explicit informational and an impact-derived one are the same
|
|
199
|
+
* thing and must not land in different buckets.
|
|
69
200
|
*/
|
|
70
201
|
function deriveSeverity(impact, severity) {
|
|
71
202
|
if (severity != null) return String(severity);
|
|
72
|
-
|
|
73
|
-
return sev === "informational" ? "none" : sev;
|
|
203
|
+
return impactToSeverity(impact);
|
|
74
204
|
}
|
|
75
205
|
function statusBucket(counts, status) {
|
|
76
206
|
switch (status) {
|
|
@@ -98,7 +228,7 @@ function addCount(counts, status, severity) {
|
|
|
98
228
|
case "low":
|
|
99
229
|
sc.low++;
|
|
100
230
|
break;
|
|
101
|
-
default: sc.
|
|
231
|
+
default: sc.informational++;
|
|
102
232
|
}
|
|
103
233
|
}
|
|
104
234
|
function statusToThresholdKey(status) {
|
|
@@ -191,11 +321,37 @@ function calculateCompliance(counts) {
|
|
|
191
321
|
return Math.round(pct * 100) / 100;
|
|
192
322
|
}
|
|
193
323
|
/**
|
|
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.
|
|
327
|
+
*/
|
|
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;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
194
349
|
* validateThresholds checks all threshold bounds against observed counts and
|
|
195
350
|
* compliance, returning human-readable violation messages (empty when all pass).
|
|
196
351
|
*/
|
|
197
352
|
function validateThresholds(config, counts, compliance, controlMap) {
|
|
198
353
|
const violations = [];
|
|
354
|
+
violations.push(...normalizeLegacySeverity(config));
|
|
199
355
|
const actualControls = /* @__PURE__ */ new Map();
|
|
200
356
|
for (const m of controlMap) actualControls.set(m.id, m);
|
|
201
357
|
if (config.compliance) {
|
|
@@ -227,7 +383,7 @@ function checkSeverityThreshold(status, threshold, actual, actualControls) {
|
|
|
227
383
|
check("high", threshold.high, actual.high);
|
|
228
384
|
check("medium", threshold.medium, actual.medium);
|
|
229
385
|
check("low", threshold.low, actual.low);
|
|
230
|
-
check("
|
|
386
|
+
check("informational", threshold.informational, actual.informational);
|
|
231
387
|
check("total", threshold.total, actual.total);
|
|
232
388
|
return violations;
|
|
233
389
|
}
|
|
@@ -295,9 +451,9 @@ function safeGlobMatch(s, pattern) {
|
|
|
295
451
|
function filter(results, options) {
|
|
296
452
|
const filters = buildFilters(options);
|
|
297
453
|
const matches = [];
|
|
298
|
-
for (const baseline of results.baselines ?? []) {
|
|
454
|
+
for (const [baselineIndex, baseline] of (results.baselines ?? []).entries()) {
|
|
299
455
|
if (options.baseline && !matchesGlob(baseline.name, options.baseline)) continue;
|
|
300
|
-
for (const control of baseline.requirements ?? []) {
|
|
456
|
+
for (const [index, control] of (baseline.requirements ?? []).entries()) {
|
|
301
457
|
if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) return matches;
|
|
302
458
|
const status = options.statusOf ? options.statusOf(control) : "";
|
|
303
459
|
const severity = deriveSeverity(control.impact, control.severity ?? null);
|
|
@@ -308,7 +464,9 @@ function filter(results, options) {
|
|
|
308
464
|
status,
|
|
309
465
|
impact: control.impact,
|
|
310
466
|
severity,
|
|
311
|
-
baseline: baseline.name
|
|
467
|
+
baseline: baseline.name,
|
|
468
|
+
baselineIndex,
|
|
469
|
+
index
|
|
312
470
|
});
|
|
313
471
|
}
|
|
314
472
|
}
|
|
@@ -620,10 +778,6 @@ function dedupe(input) {
|
|
|
620
778
|
return out;
|
|
621
779
|
}
|
|
622
780
|
//#endregion
|
|
623
|
-
|
|
624
|
-
/** Library version, kept on the workspace lockstep. */
|
|
625
|
-
const engineVersion = "3.6.0";
|
|
626
|
-
//#endregion
|
|
627
|
-
export { agentOverrideCount, agentOverridesInPackage, calculateCompliance, completeness, countControlsByStatus, countControlsByStatusSeverity, coveredBaselineNames, coveredBaselinesInPackage, deriveSeverity, detect, detectFormat, engineVersion, filter, load, mapControlIDs, mapControlIDsByStatus, overallStatus, parseEvidencePackage, plannedBaselineRefs, validateThresholds, verifyChecksums };
|
|
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 };
|
|
628
782
|
|
|
629
783
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/detect.ts","../src/compliance.ts","../src/safematch.ts","../src/query.ts","../src/loader.ts","../src/evidence.ts","../src/index.ts"],"sourcesContent":["// Document-type detection — the TypeScript peer of hdf-engine/go/detect.go.\n// Fingerprints an HDF document by its root keys and returns the schema type\n// string. Kept at behavioural parity with the Go implementation (see\n// go/detect_test.go and src/detect.test.ts, which assert both against the same\n// bundled schema examples).\n\n/** The eight HDF document type strings, matching validators.Type* in Go. */\nexport type HdfDocType =\n | 'results'\n | 'baseline'\n | 'system'\n | 'plan'\n | 'amendments'\n | 'evidence-package'\n | 'comparison'\n | 'requirement-change-event'\n | '';\n\n/**\n * Detect fingerprints an HDF document by its root keys and returns the schema\n * type string, or '' when the input is not a JSON object or matches no known\n * HDF document type.\n */\nexport function detect(input: string): HdfDocType {\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n return '';\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return '';\n }\n const doc = parsed as Record<string, unknown>;\n const has = (...keys: string[]): boolean =>\n keys.every((k) => Object.prototype.hasOwnProperty.call(doc, k));\n\n // Most specific first. A requirement-change-event carries the singular\n // requirementId together with the state/before/after triad — a combination\n // no other HDF document type has — so it is checked ahead of the rest.\n if (has('requirementId', 'state', 'before', 'after')) return 'requirement-change-event';\n\n if (has('contents')) return 'evidence-package';\n if (has('overrides')) return 'amendments';\n if (has('assessments')) return 'plan';\n if (has('comparisonMode')) return 'comparison';\n if (has('baselines')) return 'results';\n if (has('components')) return 'system';\n if (has('requirements')) return 'baseline';\n return '';\n}\n","// Compliance & threshold engine — the TypeScript peer of\n// hdf-engine/go/compliance.go. Pure functions, kept at behavioural parity with\n// the Go implementation (see test/compliance.test.ts, which runs both over the\n// same fixture). Violation message formats match the Go fmt.Sprintf output.\n\nimport type { HDFResults, EvaluatedRequirement, RequirementResult, Severity } from '@mitre/hdf-schema';\nimport { worstStatus, impactToSeverity } from '@mitre/hdf-utilities';\n\n/** Threshold status-key constants (SAF CLI-compatible keys). */\nexport const THRESHOLD_PASSED = 'passed';\nexport const THRESHOLD_FAILED = 'failed';\nexport const THRESHOLD_SKIPPED = 'skipped';\nexport const THRESHOLD_ERROR = 'error';\nexport const THRESHOLD_NO_IMPACT = 'no_impact';\n\nexport interface SeverityCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n none: number;\n total: number;\n}\n\nexport interface StatusCounts {\n passed: SeverityCounts;\n failed: SeverityCounts;\n skipped: SeverityCounts;\n error: SeverityCounts;\n noImpact: SeverityCounts;\n}\n\nexport interface ControlIDMapping {\n id: string;\n status: string;\n severity: string;\n}\n\nexport interface ThresholdBound {\n min?: number;\n max?: number;\n controls?: string[];\n}\n\nexport interface ThresholdSeverity {\n critical?: ThresholdBound;\n high?: ThresholdBound;\n medium?: ThresholdBound;\n low?: ThresholdBound;\n none?: ThresholdBound;\n total?: ThresholdBound;\n}\n\nexport interface ComplianceBound {\n min?: number;\n max?: number;\n}\n\nexport interface ThresholdConfig {\n compliance?: ComplianceBound;\n passed?: ThresholdSeverity;\n failed?: ThresholdSeverity;\n skipped?: ThresholdSeverity;\n error?: ThresholdSeverity;\n noImpact?: ThresholdSeverity;\n}\n\nfunction newSeverityCounts(): SeverityCounts {\n return { critical: 0, high: 0, medium: 0, low: 0, none: 0, total: 0 };\n}\n\nfunction newStatusCounts(): StatusCounts {\n return {\n passed: newSeverityCounts(),\n failed: newSeverityCounts(),\n skipped: newSeverityCounts(),\n error: newSeverityCounts(),\n noImpact: newSeverityCounts(),\n };\n}\n\n/**\n * overallStatus is the canonical worst-wins roll-up of a requirement's result\n * statuses, delegated to @mitre/hdf-utilities worstStatus (error > failed >\n * passed > notApplicable > notReviewed; empty → notReviewed). No local rank\n * switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).\n */\nexport function overallStatus(results: RequirementResult[]): string {\n return worstStatus(results.map((r) => String(r.status)));\n}\n\n/**\n * deriveSeverity determines the severity string from impact and optional explicit\n * severity, using impactToSeverity. Maps \"informational\" to \"none\".\n */\nexport function deriveSeverity(impact: number, severity?: Severity | null): string {\n // Presence-based, matching Go DeriveSeverity's `if severity != nil`: an explicit\n // severity — including an empty string — is returned verbatim; only a\n // null/undefined severity derives from impact. Testing truthiness here would\n // send \"\" through the impact path and diverge from Go (bead 4908.20).\n if (severity != null) {\n return String(severity);\n }\n const sev = impactToSeverity(impact);\n return sev === 'informational' ? 'none' : sev;\n}\n\nfunction statusBucket(counts: StatusCounts, status: string): SeverityCounts {\n switch (status) {\n case 'passed':\n return counts.passed;\n case 'failed':\n return counts.failed;\n case 'error':\n return counts.error;\n case 'notApplicable':\n return counts.noImpact;\n case 'notReviewed':\n return counts.skipped;\n default:\n return counts.skipped;\n }\n}\n\nfunction addCount(counts: StatusCounts, status: string, severity: string): void {\n const sc = statusBucket(counts, status);\n sc.total++;\n switch (severity) {\n case 'critical':\n sc.critical++;\n break;\n case 'high':\n sc.high++;\n break;\n case 'medium':\n sc.medium++;\n break;\n case 'low':\n sc.low++;\n break;\n default:\n sc.none++;\n }\n}\n\nfunction statusToThresholdKey(status: string): string {\n switch (status) {\n case 'passed':\n return THRESHOLD_PASSED;\n case 'failed':\n return THRESHOLD_FAILED;\n case 'notReviewed':\n return THRESHOLD_SKIPPED;\n case 'error':\n return THRESHOLD_ERROR;\n case 'notApplicable':\n return THRESHOLD_NO_IMPACT;\n default:\n return THRESHOLD_SKIPPED;\n }\n}\n\n/** CountControlsByStatusSeverity counts requirements by overall status and severity. */\nexport function countControlsByStatusSeverity(results: HDFResults): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n addCount(counts, overallStatus(req.results ?? []), deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * countControlsByStatus counts requirements by a caller-resolved status — the\n * injected-resolver twin of countControlsByStatusSeverity (which counts raw\n * result statuses with no override awareness). statusOf returns each\n * requirement's status in the schema vocabulary (passed/failed/notApplicable/\n * notReviewed/error); an empty or unrecognized value counts as skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status rollups\n * (e.g. compliance with and without agent-attributed overrides) without the\n * engine binding to any one status convention. Parity: go/compliance.go.\n */\nexport function countControlsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n addCount(counts, status, deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * agentOverrideCount counts the status overrides across a result set whose\n * applied-by identity type is \"agent\" — the detective count. Deterministic\n * from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny\n * signal. Parity: go/compliance.go AgentOverrideCount.\n */\nexport function agentOverrideCount(results: HDFResults): number {\n let count = 0;\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n for (const o of req.statusOverrides ?? []) {\n if (o.appliedBy?.type === 'agent') {\n count++;\n }\n }\n }\n }\n return count;\n}\n\n/** MapControlIDs builds control ID → status/severity mappings from a result set. */\nexport function mapControlIDs(results: HDFResults): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = overallStatus(req.results ?? []);\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: deriveSeverity(req.impact, reqSeverity(req)),\n });\n }\n }\n return mappings;\n}\n\n/**\n * mapControlIDsByStatus builds control ID → status/severity mappings using a\n * caller-resolved status — the injected-resolver twin of mapControlIDs (which\n * maps raw result statuses). statusOf returns each requirement's status in the\n * schema vocabulary; an empty or unrecognized value maps to skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status control\n * listings (the same injection pattern as countControlsByStatus). Parity:\n * go/compliance.go MapControlIDsByStatus.\n */\nexport function mapControlIDsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: deriveSeverity(req.impact, reqSeverity(req)),\n });\n }\n }\n return mappings;\n}\n\nfunction reqSeverity(req: EvaluatedRequirement): Severity | null {\n return (req.severity ?? null) as Severity | null;\n}\n\n/**\n * calculateCompliance returns the compliance percentage rounded to two decimals:\n * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.\n */\nexport function calculateCompliance(counts: StatusCounts): number {\n const relevant = counts.passed.total + counts.failed.total + counts.skipped.total + counts.error.total;\n if (relevant === 0) {\n return 0;\n }\n const pct = (counts.passed.total / relevant) * 100;\n return Math.round(pct * 100) / 100;\n}\n\n/**\n * validateThresholds checks all threshold bounds against observed counts and\n * compliance, returning human-readable violation messages (empty when all pass).\n */\nexport function validateThresholds(\n config: ThresholdConfig,\n counts: StatusCounts,\n compliance: number,\n controlMap: ControlIDMapping[],\n): string[] {\n const violations: string[] = [];\n\n const actualControls = new Map<string, ControlIDMapping>();\n for (const m of controlMap) {\n actualControls.set(m.id, m);\n }\n\n if (config.compliance) {\n if (config.compliance.min !== undefined && compliance < config.compliance.min) {\n violations.push(`compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`);\n }\n if (config.compliance.max !== undefined && compliance > config.compliance.max) {\n violations.push(`compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`);\n }\n }\n\n violations.push(...checkSeverityThreshold(THRESHOLD_PASSED, config.passed, counts.passed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_FAILED, config.failed, counts.failed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_SKIPPED, config.skipped, counts.skipped, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_ERROR, config.error, counts.error, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_NO_IMPACT, config.noImpact, counts.noImpact, actualControls));\n\n return violations;\n}\n\nfunction checkSeverityThreshold(\n status: string,\n threshold: ThresholdSeverity | undefined,\n actual: SeverityCounts,\n actualControls: Map<string, ControlIDMapping>,\n): string[] {\n if (!threshold) {\n return [];\n }\n const violations: string[] = [];\n const check = (label: string, bound: ThresholdBound | undefined, actualCount: number): void => {\n if (!bound) {\n return;\n }\n const path = `${status}.${label}`;\n if (bound.min !== undefined && actualCount < bound.min) {\n violations.push(`${path}: ${actualCount} is below minimum ${bound.min}`);\n }\n if (bound.max !== undefined && actualCount > bound.max) {\n violations.push(`${path}: ${actualCount} exceeds maximum ${bound.max}`);\n }\n for (const expectedID of bound.controls ?? []) {\n const ac = actualControls.get(expectedID);\n if (!ac) {\n violations.push(`${path}: expected control ${expectedID} not found in results`);\n } else if (ac.status !== status || ac.severity !== label) {\n violations.push(\n `${path}: control ${expectedID} expected ${status}/${label} but found ${ac.status}/${ac.severity}`,\n );\n }\n }\n };\n\n check('critical', threshold.critical, actual.critical);\n check('high', threshold.high, actual.high);\n check('medium', threshold.medium, actual.medium);\n check('low', threshold.low, actual.low);\n check('none', threshold.none, actual.none);\n check('total', threshold.total, actual.total);\n\n return violations;\n}\n","// Glob matching — the TypeScript peer of hdf-engine/go/safematch.go. Kept at\n// behavioural parity with the Go matcher.\n\nconst MAX_PATTERN_LENGTH = 256;\n\nconst REGEX_SPECIAL = new Set(['.', '+', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\\\']);\n\n/**\n * globToRegex converts a glob pattern (with * and ? wildcards) to an anchored\n * regular expression, escaping every other regex metacharacter exactly once. A\n * single pass avoids re-escaping the backslash introduced by escaping an earlier\n * metacharacter (the doubled-backslash defect that made any dotted pattern match\n * nothing).\n */\nexport function globToRegex(glob: string): string {\n let result = '^';\n for (const ch of glob) {\n if (ch === '*') {\n result += '.*';\n } else if (ch === '?') {\n result += '.';\n } else if (REGEX_SPECIAL.has(ch)) {\n result += '\\\\' + ch;\n } else {\n result += ch;\n }\n }\n return result + '$';\n}\n\n/**\n * safeGlobMatch converts a glob pattern to a regex and matches case-insensitively.\n * Returns false for over-length or invalid patterns (fail-safe), mirroring the\n * Go matcher's length cap and error handling.\n */\nconst byteEncoder = new TextEncoder();\n\n/** byteLength returns the UTF-8 byte length, matching Go's len(string). */\nfunction byteLength(s: string): number {\n return byteEncoder.encode(s).length;\n}\n\nexport function safeGlobMatch(s: string, pattern: string): boolean {\n // Cap on UTF-8 byte length (matching Go's len(pattern)), and — like Go's\n // compileSafeRegex — re-cap the EXPANDED regex, so an over-length glob or a\n // small glob that expands past the limit is rejected identically in both\n // languages (not just capped on the raw glob's UTF-16 length).\n if (byteLength(pattern) > MAX_PATTERN_LENGTH) {\n return false;\n }\n const rx = globToRegex(pattern);\n if (byteLength(rx) > MAX_PATTERN_LENGTH) {\n return false;\n }\n let re: RegExp;\n try {\n re = new RegExp(rx, 'i');\n } catch {\n return false;\n }\n return re.test(s);\n}\n","// Requirements query engine — the TypeScript peer of hdf-engine/go/filter.go.\n// A pure filter(results, options) with no shared mutable state, kept at\n// behavioural parity with the Go implementation (see test/query.test.ts, which\n// runs both over the same fixture).\n\nimport type { HDFResults, EvaluatedRequirement } from '@mitre/hdf-schema';\nimport { deriveSeverity } from './compliance.js';\nimport { safeGlobMatch } from './safematch.js';\n\n/**\n * FilterOptions configures a requirements query. Every filter input arrives here;\n * distinct filters combine with AND, repeated values within a filter with OR.\n * statusOf resolves a requirement's display status, injected so the engine stays\n * agnostic to the caller's status-string convention (undefined → empty status).\n */\nexport interface FilterOptions {\n status?: string[];\n severity?: string[];\n impact?: string;\n cci?: string[];\n nist?: string[];\n id?: string;\n tag?: string[];\n search?: string;\n baseline?: string;\n limit?: number;\n count?: boolean;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/** A single query result row. */\nexport interface Match {\n id: string;\n title: string;\n status: string;\n impact: number;\n severity: string;\n baseline: string;\n}\n\ntype FilterFunc = (control: EvaluatedRequirement, status: string, severity: string) => boolean;\n\n/**\n * filter returns the requirements across the result set's baselines that satisfy\n * options. Applies to requirement collections (results/baseline documents); the\n * calling adapter rejects document types that carry no requirements.\n */\nexport function filter(results: HDFResults, options: FilterOptions): Match[] {\n const filters = buildFilters(options);\n const matches: Match[] = [];\n\n for (const baseline of results.baselines ?? []) {\n if (options.baseline && !matchesGlob(baseline.name, options.baseline)) {\n continue;\n }\n for (const control of baseline.requirements ?? []) {\n if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) {\n return matches;\n }\n\n const status = options.statusOf ? options.statusOf(control) : '';\n // Explicit STIG severity wins; impact-derived only as a fallback — the\n // canonical rule shared with the compliance counts (deriveSeverity), so\n // query rows and compliance never disagree on a requirement's severity.\n const severity = deriveSeverity(control.impact, control.severity ?? null);\n\n if (!applyFilters(control, status, severity, filters)) {\n continue;\n }\n\n matches.push({\n id: control.id,\n title: control.title ?? '',\n status,\n impact: control.impact,\n severity,\n baseline: baseline.name,\n });\n }\n }\n return matches;\n}\n\nfunction buildFilters(options: FilterOptions): FilterFunc[] {\n const filters: FilterFunc[] = [];\n\n if (options.status && options.status.length > 0) {\n const statuses = options.status.map((s) => s.toLowerCase());\n filters.push((_c, s) => statuses.includes(s.toLowerCase()));\n }\n\n if (options.severity && options.severity.length > 0) {\n const severities = options.severity.map((s) => s.toLowerCase());\n filters.push((_c, _s, severity) => severities.includes(severity));\n }\n\n if (options.impact) {\n const [op, val] = parseImpactFilter(options.impact);\n filters.push((c) => compareImpact(c.impact, op, val));\n }\n\n if (options.cci && options.cci.length > 0) {\n const ccis = options.cci.map((c) => c.toUpperCase());\n filters.push((c) => ccis.some((cci) => tagContains(c.tags, 'cci', cci)));\n }\n\n if (options.nist && options.nist.length > 0) {\n const nist = options.nist;\n filters.push((c) => nist.some((n) => tagMatchesGlob(c.tags, 'nist', n)));\n }\n\n if (options.id) {\n const id = options.id;\n filters.push(\n (c) =>\n tagContains(c.tags, 'stig_id', id) ||\n tagContains(c.tags, 'gid', id) ||\n tagContains(c.tags, 'gtitle', id) ||\n c.id === id,\n );\n }\n\n if (options.tag && options.tag.length > 0) {\n const tagFilters: { key: string; value: string }[] = [];\n for (const t of options.tag) {\n const idx = t.indexOf(':');\n if (idx >= 0) {\n tagFilters.push({ key: t.slice(0, idx), value: t.slice(idx + 1) });\n }\n }\n if (tagFilters.length > 0) {\n filters.push((c) => tagFilters.some((tf) => tagMatchesGlob(c.tags, tf.key, tf.value)));\n }\n }\n\n if (options.search) {\n const search = options.search.toLowerCase();\n filters.push((c) => {\n if (c.id.toLowerCase().includes(search)) return true;\n if (c.title && c.title.toLowerCase().includes(search)) return true;\n for (const desc of c.descriptions ?? []) {\n if (desc.data.toLowerCase().includes(search)) return true;\n }\n return false;\n });\n }\n\n return filters;\n}\n\nfunction applyFilters(\n control: EvaluatedRequirement,\n status: string,\n severity: string,\n filters: FilterFunc[],\n): boolean {\n return filters.every((f) => f(control, status, severity));\n}\n\n// DECIMAL_FLOAT is the shared impact-filter operand grammar — a plain decimal:\n// optional sign, digits with an optional fraction (or a leading-dot fraction),\n// optional decimal exponent. It excludes the forms JS Number() accepts but that\n// make no sense as a 0.0–1.0 threshold and diverge from Go strconv.ParseFloat:\n// hex/binary/octal integers (0x1f→31, 0b101→5, 0o17→15) and Infinity. The Go\n// engine applies the identical pattern so a filter is accepted or rejected the\n// same in both languages (bead 4908.15).\nconst DECIMAL_FLOAT = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n// parseDecimal parses a plain-decimal operand, returning null for anything\n// outside the shared grammar (including overflow to Infinity, e.g. '1e400', so\n// Go's ParseFloat ErrRange rejection is mirrored).\nfunction parseDecimal(s: string): number | null {\n if (!DECIMAL_FLOAT.test(s)) return null;\n const v = Number(s);\n return Number.isFinite(v) ? v : null;\n}\n\n// An invalid operand safe-degrades to ('=', NaN), which compareImpact treats as\n// matching NOTHING — mirroring the Go engine's `return ok && compareImpact(...)`.\n// It must never coerce to ('=', 0), which silently returns confidently-wrong\n// impact==0 rows for a typo'd or garbage filter.\nexport function parseImpactFilter(f: string): [string, number] {\n const trimmed = f.trim();\n for (const op of ['>=', '<=', '>', '<', '=']) {\n if (trimmed.startsWith(op)) {\n const v = parseDecimal(trimmed.slice(op.length).trim());\n return v === null ? ['=', NaN] : [op, v];\n }\n }\n const v = parseDecimal(trimmed);\n return v === null ? ['=', NaN] : ['=', v];\n}\n\nexport function compareImpact(impact: number, op: string, val: number): boolean {\n switch (op) {\n case '>':\n return impact > val;\n case '>=':\n return impact >= val;\n case '<':\n return impact < val;\n case '<=':\n return impact <= val;\n case '=':\n return impact === val;\n default:\n return false;\n }\n}\n\nexport function tagContains(tags: Record<string, unknown>, key: string, value: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n const want = value.toLowerCase();\n if (typeof tagVal === 'string') {\n return tagVal.toLowerCase() === want;\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && item.toLowerCase() === want);\n }\n return false;\n}\n\nexport function tagMatchesGlob(tags: Record<string, unknown>, key: string, pattern: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n if (typeof tagVal === 'string') {\n return safeGlobMatch(tagVal, pattern);\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && safeGlobMatch(item, pattern));\n }\n return false;\n}\n\n/** matchesGlob reports whether s matches the glob pattern (case-insensitive). */\nexport function matchesGlob(s: string, pattern: string): boolean {\n return safeGlobMatch(s, pattern);\n}\n","// Document loader engine core — the TypeScript peer of hdf-engine/go/loader.go,\n// kept at behavioural parity (see loader.test.ts + the Go parity test, which\n// run both over the same fixtures). Pure and schema-typed: size-guard first,\n// wire-format + document-type detection, then the canonical parse for the\n// results/baseline types. No cache, no degraded envelope — those are MCP\n// concerns layered on top in hdf-cli/internal/mcp/loader.\n\nimport type { HDFResults, HDFBaseline } from '@mitre/hdf-schema';\nimport { validateInputSize } from '@mitre/hdf-utilities';\nimport { parseResults, parseBaseline } from '@mitre/hdf-parsers';\nimport { detect, type HdfDocType } from './detect.js';\n\n/** Wire encoding of loader input (parity with Go InputFormat). */\nexport type InputFormat = 'json' | 'ndjson';\n\nexport interface LoadResult {\n format: InputFormat;\n docType: HdfDocType;\n results?: HDFResults;\n baseline?: HDFBaseline;\n /** Non-empty when detected as results/baseline but the parse/validate failed. */\n parseError?: string;\n valid: boolean;\n}\n\n/**\n * load is the schema-typed loader core. In order: validateInputSize (FIRST,\n * before any parse; maxSize <= 0 uses the default), wire-format detection\n * (JSON vs NDJSON), document-type detection (detect), then the canonical\n * hdf-parsers parse for the results and baseline types. Other types are\n * detected but not parsed here.\n */\nexport function load(input: string | Uint8Array, maxSize = 0): LoadResult {\n validateInputSize(input, maxSize); // first op — throws on oversize\n\n const text = typeof input === 'string' ? input : new TextDecoder().decode(input);\n const result: LoadResult = {\n format: detectFormat(text),\n docType: detect(text),\n valid: false,\n };\n\n if (result.docType === 'results') {\n const r = parseResults(text);\n if (r.success && r.data) {\n result.results = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n } else if (result.docType === 'baseline') {\n const r = parseBaseline(text);\n if (r.success && r.data) {\n result.baseline = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n }\n\n return result;\n}\n\n/**\n * detectFormat classifies input as a single JSON document or newline-delimited\n * JSON, consistent with the Go core: NDJSON is two or more non-blank lines that\n * each independently parse as a complete JSON value. A pretty-printed single\n * object stays 'json' (its first line is not itself a complete JSON value).\n */\nexport function detectFormat(text: string): InputFormat {\n const lines = text.split('\\n').filter((l) => l.trim() !== '');\n const [first, second] = lines;\n if (first === undefined || second === undefined) {\n return 'json';\n }\n if (isCompleteJSON(first) && isCompleteJSON(second)) {\n return 'ndjson';\n }\n return 'json';\n}\n\n// isCompleteJSON reports whether s is a single complete JSON value with no\n// trailing content — the per-line test the NDJSON classifier applies. JSON.parse\n// already rejects trailing garbage, so a successful parse is sufficient.\nfunction isCompleteJSON(s: string): boolean {\n try {\n JSON.parse(s);\n return true;\n } catch {\n return false;\n }\n}\n","// Evidence-verify engine — the TypeScript peer of hdf-engine/go/evidence.go.\n// Pure, filesystem-agnostic core of `hdf evidence verify` (ADR-0007 §11):\n// content-checksum classification and plan/results completeness. All filesystem\n// IO and path confinement stay in the caller, injected as a FetchFn. Kept at\n// behavioural parity with the Go implementation (see test/evidence.test.ts,\n// which runs both over the same fixtures).\n\nimport { createHash } from 'node:crypto';\nimport { agentOverrideCount } from './compliance.js';\nimport type { HDFResults } from '@mitre/hdf-schema';\n\n/** Classifies a single content entry's checksum verification. */\nexport type ChecksumStatus = 'match' | 'mismatch' | 'skipped' | 'error';\n\n/** One content entry of an evidence package: a referenced document and its\n * recorded checksum ('' when the entry carries none). */\nexport interface EvidenceContent {\n uri: string;\n type: string;\n checksum: string;\n}\n\n/** The verification outcome for one content entry. */\nexport interface ChecksumResult {\n uri: string;\n type: string;\n status: ChecksumStatus;\n expected?: string;\n actual?: string;\n error?: string;\n}\n\n/** Reports which planned baselines are covered by results. */\nexport interface CompletenessResult {\n planned: string[];\n covered: string[];\n missing: string[];\n complete: boolean;\n}\n\n/** Resolves a content URI to its bytes. The caller owns path confinement\n * (HDF_MCP_ROOT for the MCP, the package directory for the CLI). Throws when the\n * uri cannot be read. */\nexport type FetchFn = (uri: string) => Uint8Array;\n\ntype RawObject = Record<string, unknown>;\n\n/** Go decodes into a typed struct, so a JSON `null` document leaves zero values\n * while a wrong-typed one is a decode error. These three helpers give the TS\n * peer the same split instead of asserting a shape onto untrusted input. */\nfunction parseDocument(text: string, what: string): RawObject {\n const doc: unknown = JSON.parse(text);\n if (doc === null) return {};\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(doc)} into an object`);\n }\n return doc as RawObject;\n}\n\nfunction objectArray(value: unknown, what: string, field: string): RawObject[] {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(value)} into ${field}`);\n }\n return value.map((entry: unknown) => {\n if (entry === null) return {};\n if (typeof entry !== 'object' || Array.isArray(entry)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(entry)} into a ${field} entry`);\n }\n return entry as RawObject;\n });\n}\n\nfunction str(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction describe(value: unknown): string {\n return Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;\n}\n\n/** Extracts the planRef and content entries from an evidence-package document. */\nexport function parseEvidencePackage(pkg: string): { planRef: string; contents: EvidenceContent[] } {\n const doc = parseDocument(pkg, 'evidence package');\n const contents: EvidenceContent[] = objectArray(doc.contents, 'evidence package', 'contents').map((c) => {\n const checksum = c.checksum;\n return {\n uri: str(c.uri),\n type: str(c.type),\n checksum: typeof checksum === 'object' && checksum !== null ? str((checksum as RawObject).value) : '',\n };\n });\n return { planRef: str(doc.planRef), contents };\n}\n\n/** Verifies each content entry's sha256 against fetch(uri), preserving entry\n * order. No checksum → skipped; a fetch throw → error; hash mismatch → mismatch\n * (carrying expected+actual). */\nexport function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): ChecksumResult[] {\n return contents.map((c) => {\n const r: ChecksumResult = { uri: c.uri, type: c.type, status: 'skipped' };\n if (c.checksum === '') {\n return r;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch (e) {\n return { ...r, status: 'error', error: e instanceof Error ? e.message : String(e) };\n }\n const actual = sha256Hex(data);\n if (actual === c.checksum) {\n return { ...r, status: 'match' };\n }\n return { ...r, status: 'mismatch', expected: c.checksum, actual };\n });\n}\n\n/** Extracts assessment baselineRefs from a plan document, deduped in first-seen\n * order. */\nexport function plannedBaselineRefs(plan: string): string[] {\n const doc = parseDocument(plan, 'plan');\n const refs = objectArray(doc.assessments, 'plan', 'assessments')\n .map((a) => str(a.baselineRef))\n .filter((s) => s !== '');\n return dedupe(refs);\n}\n\n/** Extracts baseline names from a results document, deduped in first-seen order. */\nexport function coveredBaselineNames(results: string): string[] {\n const doc = parseDocument(results, 'results');\n const names = objectArray(doc.baselines, 'results', 'baselines')\n .map((b) => str(b.name))\n .filter((s) => s !== '');\n return dedupe(names);\n}\n\n/** Concatenates the covered baseline names of every hdf-results document the\n * package references, in entry order. An entry that cannot be fetched or parsed\n * is skipped: checksum verification is what reports a read failure, and a\n * partial coverage list is what the completeness diff needs. */\nexport function coveredBaselinesInPackage(contents: EvidenceContent[], fetch: FetchFn): string[] {\n const covered: string[] = [];\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n covered.push(...coveredBaselineNames(text));\n } catch {\n return;\n }\n });\n return covered;\n}\n\n/** Sums the agent-attributed override count across every hdf-results document\n * the package references. Unreadable or unparseable entries are skipped. */\nexport function agentOverridesInPackage(contents: EvidenceContent[], fetch: FetchFn): number {\n let total = 0;\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n total += agentOverrideCount(JSON.parse(text) as HDFResults);\n } catch {\n return;\n }\n });\n return total;\n}\n\n/** Fetches each referenced hdf-results document in entry order, skipping\n * entries that carry no uri or cannot be read. */\nfunction forEachResultsDocument(\n contents: EvidenceContent[],\n fetch: FetchFn,\n visit: (text: string) => void\n): void {\n for (const c of contents) {\n if (c.type !== 'hdf-results' || c.uri === '') {\n continue;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch {\n continue;\n }\n visit(new TextDecoder().decode(data));\n }\n}\n\n/** Diffs planned baseline refs against covered baseline names. A planned ref is\n * covered when some results baseline shares its name. Missing is sorted so the\n * outcome is deterministic across languages and runs. */\nexport function completeness(planned: string[], covered: string[]): CompletenessResult {\n const coveredSet = new Set(covered);\n const missing = planned.filter((p) => !coveredSet.has(p)).sort();\n return { planned, covered, missing, complete: missing.length === 0 };\n}\n\nfunction sha256Hex(data: Uint8Array): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\nfunction dedupe(input: string[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const s of input) {\n if (!seen.has(s)) {\n seen.add(s);\n out.push(s);\n }\n }\n return out;\n}\n","// @mitre/hdf-engine — shared, schema-typed read-side engines for HDF documents\n// (detect, query, compliance, and future read-side engines). Consumed as a\n// library by the CLI and the MCP; sibling to @mitre/hdf-diff. See ADR-0007.\n\n/** Library version, kept on the workspace lockstep. */\nexport const engineVersion = '3.6.0';\n\n// Detection engine (peer of hdf-engine/go/detect.go).\nexport { detect, type HdfDocType } from './detect.js';\n\n// Query engine (peer of hdf-engine/go/filter.go).\nexport { filter, type FilterOptions, type Match } from './query.js';\n\n// Document loader core (peer of hdf-engine/go/loader.go).\nexport { load, detectFormat, type InputFormat, type LoadResult } from './loader.js';\n\n// Evidence-verify engine (peer of hdf-engine/go/evidence.go).\nexport {\n parseEvidencePackage,\n verifyChecksums,\n plannedBaselineRefs,\n coveredBaselineNames,\n coveredBaselinesInPackage,\n agentOverridesInPackage,\n completeness,\n type ChecksumStatus,\n type EvidenceContent,\n type ChecksumResult,\n type CompletenessResult,\n type FetchFn,\n} from './evidence.js';\n\n// Compliance & threshold engine (peer of hdf-engine/go/compliance.go).\nexport {\n countControlsByStatusSeverity,\n countControlsByStatus,\n agentOverrideCount,\n mapControlIDs,\n mapControlIDsByStatus,\n calculateCompliance,\n validateThresholds,\n overallStatus,\n deriveSeverity,\n type StatusCounts,\n type SeverityCounts,\n type ControlIDMapping,\n type ThresholdConfig,\n type ThresholdSeverity,\n type ThresholdBound,\n type ComplianceBound,\n} from './compliance.js';\n"],"mappings":";;;;;;;;;AAuBA,SAAgB,OAAO,OAA2B;CAChD,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,KAAK;CAC3B,QAAQ;EACN,OAAO;CACT;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GACvE,OAAO;CAET,MAAM,MAAM;CACZ,MAAM,OAAO,GAAG,SACd,KAAK,OAAO,MAAM,OAA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ge.ts","../src/detect.ts","../src/compliance.ts","../src/safematch.ts","../src/query.ts","../src/loader.ts","../src/evidence.ts"],"sourcesContent":["// Library version, kept on the workspace lockstep with package.json (the Go\n// peer is hdf-engine/go/engine.go Version(); index.test.ts pins both to\n// package.json). It lives in its own module so engines that stamp it into\n// documents (merge.ts) can import it without a cycle through index.ts.\nexport const engineVersion = '3.7.0';\n","// Merge engine — the TypeScript peer of hdf-engine/go/merge.go (ADR-0016).\n// Combines several results documents into one multi-baseline results document:\n// one baseline per input baseline renamed `<tool>/<original>`, per-baseline\n// provenance in labels, each input's root provenance verbatim under\n// extensions[\"hdf-merge\"]. Union semantics — nothing deduplicated, re-keyed or\n// dropped. Deterministic for the same inputs in the same order. Kept at\n// behavioural parity with Go (see test/merge.test.ts / go/merge_test.go).\n\nimport type { HDFResults, EvaluatedBaseline, Component } from '@mitre/hdf-schema';\nimport { engineVersion } from './version.js';\n\n/** One input to merge: a results document and the name it is recorded under. */\nexport interface MergeSource {\n name: string;\n doc: HDFResults;\n}\n\nexport type MergeWarningKind = 'duplicate-baseline-name' | 'label-overwritten';\n\n/** A non-fatal condition merge reports rather than silently resolving. */\nexport interface MergeWarning {\n kind: MergeWarningKind;\n /** Merged baseline name. */\n name: string;\n /** Merged baseline positions. */\n indices: number[];\n /** Set for label warnings only: the label key that was replaced or removed. */\n label?: string;\n}\n\nexport interface MergeResult {\n results: HDFResults;\n warnings: MergeWarning[];\n}\n\n/** Provenance label keys written on every merged baseline (ADR-0016 §3). */\nexport const LABEL_TOOL = 'tool';\nexport const LABEL_TOOL_VERSION = 'toolVersion';\nexport const LABEL_SOURCE_DOCUMENT = 'sourceDocument';\n\nconst MERGE_GENERATOR_NAME = 'hdf-merge';\nconst MERGE_EXTENSION_KEY = 'hdf-merge';\n\n/**\n * merge combines the sources, in order, into one results document. Returns the\n * document and any warnings (a collision or overwrite is never an error);\n * throws only when there is nothing to merge. Inputs are not mutated.\n */\nexport function merge(sources: MergeSource[]): MergeResult {\n if (sources.length === 0) {\n throw new Error('merge: no sources');\n }\n\n const baselines: EvaluatedBaseline[] = [];\n const components: Component[] = [];\n const warnings: MergeWarning[] = [];\n const seenComponent = new Set<string>();\n const provenance: Record<string, unknown>[] = [];\n const positionsByName = new Map<string, number[]>();\n let latest: HDFResults['timestamp'];\n\n sources.forEach((src, index) => {\n const prefix = toolPrefix(src.doc, index);\n const version = toolVersion(src.doc);\n\n for (const b of src.doc.baselines ?? []) {\n const name = `${prefix}/${b.name}`;\n const pos = baselines.length;\n const labels: Record<string, string> = { ...(b.labels ?? {}) };\n\n setLabel(warnings, labels, LABEL_TOOL, prefix, name, pos);\n if (version !== '') {\n setLabel(warnings, labels, LABEL_TOOL_VERSION, version, name, pos);\n } else if (LABEL_TOOL_VERSION in labels) {\n delete labels[LABEL_TOOL_VERSION];\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: LABEL_TOOL_VERSION });\n }\n setLabel(warnings, labels, LABEL_SOURCE_DOCUMENT, src.name, name, pos);\n\n const positions = positionsByName.get(name);\n if (positions) positions.push(pos);\n else positionsByName.set(name, [pos]);\n\n baselines.push({ ...b, name, labels });\n }\n\n for (const c of src.doc.components ?? []) {\n if (c.componentId !== undefined) {\n if (seenComponent.has(c.componentId)) continue;\n seenComponent.add(c.componentId);\n }\n components.push(c);\n }\n\n if (src.doc.timestamp !== undefined && (latest === undefined || millis(src.doc.timestamp) > millis(latest))) {\n latest = src.doc.timestamp;\n }\n\n provenance.push(sourceProvenance(index, src));\n });\n\n for (const [name, positions] of positionsByName) {\n if (positions.length > 1) {\n warnings.push({ kind: 'duplicate-baseline-name', name, indices: positions });\n }\n }\n\n // Key order is fixed so the same inputs serialize identically on every run.\n const results: HDFResults = {\n baselines,\n ...(components.length > 0 ? { components } : {}),\n extensions: { [MERGE_EXTENSION_KEY]: { version: engineVersion, sources: provenance } },\n generator: { name: MERGE_GENERATOR_NAME, version: engineVersion },\n ...(latest !== undefined ? { timestamp: latest } : {}),\n };\n return { results, warnings };\n}\n\nfunction setLabel(\n warnings: MergeWarning[],\n labels: Record<string, string>,\n key: string,\n value: string,\n name: string,\n pos: number,\n): void {\n if (key in labels) {\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: key });\n }\n labels[key] = value;\n}\n\n/** `<tool>` of a merged baseline name: tool.name → generator.name → doc<N>, lower-cased and trimmed. */\nfunction toolPrefix(doc: HDFResults, index: number): string {\n const tool = normalizeName(doc.tool?.name);\n if (tool !== '') return tool;\n const generator = normalizeName(doc.generator?.name);\n if (generator !== '') return generator;\n return `doc${index}`;\n}\n\nfunction normalizeName(s: string | undefined): string {\n return (s ?? '').trim().toLowerCase();\n}\n\n/**\n * millis reads a document timestamp for comparison. The schema type is Date,\n * but a document parsed from JSON carries the RFC 3339 string verbatim (the\n * loader does not revive dates), so both are accepted; the value itself is\n * carried through unchanged so output stays byte-faithful to the input.\n */\nfunction millis(ts: Date | string): number {\n return ts instanceof Date ? ts.getTime() : Date.parse(ts);\n}\n\nfunction toolVersion(doc: HDFResults): string {\n return (doc.tool?.version ?? '').trim();\n}\n\n/** One input's root metadata, verbatim, for extensions[\"hdf-merge\"].sources[]. */\nfunction sourceProvenance(index: number, src: MergeSource): Record<string, unknown> {\n const entry: Record<string, unknown> = { index, name: src.name };\n if (src.doc.tool !== undefined) entry.tool = src.doc.tool;\n if (src.doc.generator !== undefined) entry.generator = src.doc.generator;\n if (src.doc.timestamp !== undefined) entry.timestamp = src.doc.timestamp;\n if (src.doc.runner !== undefined) entry.runner = src.doc.runner;\n return entry;\n}\n","// Document-type detection — the TypeScript peer of hdf-engine/go/detect.go.\n// Fingerprints an HDF document by its root keys and returns the schema type\n// string. Kept at behavioural parity with the Go implementation (see\n// go/detect_test.go and src/detect.test.ts, which assert both against the same\n// bundled schema examples).\n\n/** The eight HDF document type strings, matching validators.Type* in Go. */\nexport type HdfDocType =\n | 'results'\n | 'baseline'\n | 'system'\n | 'plan'\n | 'amendments'\n | 'evidence-package'\n | 'comparison'\n | 'requirement-change-event'\n | '';\n\n/**\n * Detect fingerprints an HDF document by its root keys and returns the schema\n * type string, or '' when the input is not a JSON object or matches no known\n * HDF document type.\n */\nexport function detect(input: string): HdfDocType {\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n return '';\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return '';\n }\n const doc = parsed as Record<string, unknown>;\n const has = (...keys: string[]): boolean =>\n keys.every((k) => Object.prototype.hasOwnProperty.call(doc, k));\n\n // Most specific first. A requirement-change-event carries the singular\n // requirementId together with the state/before/after triad — a combination\n // no other HDF document type has — so it is checked ahead of the rest.\n if (has('requirementId', 'state', 'before', 'after')) return 'requirement-change-event';\n\n if (has('contents')) return 'evidence-package';\n if (has('overrides')) return 'amendments';\n if (has('assessments')) return 'plan';\n if (has('comparisonMode')) return 'comparison';\n if (has('baselines')) return 'results';\n if (has('components')) return 'system';\n if (has('requirements')) return 'baseline';\n return '';\n}\n","// Compliance & threshold engine — the TypeScript peer of\n// hdf-engine/go/compliance.go. Pure functions, kept at behavioural parity with\n// the Go implementation (see test/compliance.test.ts, which runs both over the\n// same fixture). Violation message formats match the Go fmt.Sprintf output.\n\nimport type { HDFResults, EvaluatedRequirement, RequirementResult, Severity } from '@mitre/hdf-schema';\nimport { worstStatus, impactToSeverity } from '@mitre/hdf-utilities';\n\n/** Threshold status-key constants (SAF CLI-compatible keys). */\nexport const THRESHOLD_PASSED = 'passed';\nexport const THRESHOLD_FAILED = 'failed';\nexport const THRESHOLD_SKIPPED = 'skipped';\nexport const THRESHOLD_ERROR = 'error';\nexport const THRESHOLD_NO_IMPACT = 'no_impact';\n\nexport interface SeverityCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n /** The schema's fifth severity; also absorbs a severity that cannot be derived or is not in the enum. */\n informational: number;\n total: number;\n}\n\nexport interface StatusCounts {\n passed: SeverityCounts;\n failed: SeverityCounts;\n skipped: SeverityCounts;\n error: SeverityCounts;\n noImpact: SeverityCounts;\n}\n\nexport interface ControlIDMapping {\n id: string;\n status: string;\n severity: string;\n}\n\nexport interface ThresholdBound {\n min?: number;\n max?: number;\n controls?: string[];\n}\n\nexport interface ThresholdSeverity {\n critical?: ThresholdBound;\n high?: ThresholdBound;\n medium?: ThresholdBound;\n low?: ThresholdBound;\n informational?: ThresholdBound;\n /** Pre-3.7 spelling of `informational`, normalized on read and never written. */\n none?: ThresholdBound;\n total?: ThresholdBound;\n}\n\nexport interface ComplianceBound {\n min?: number;\n max?: number;\n}\n\nexport interface ThresholdConfig {\n compliance?: ComplianceBound;\n passed?: ThresholdSeverity;\n failed?: ThresholdSeverity;\n skipped?: ThresholdSeverity;\n error?: ThresholdSeverity;\n noImpact?: ThresholdSeverity;\n}\n\nfunction newSeverityCounts(): SeverityCounts {\n return { critical: 0, high: 0, medium: 0, low: 0, informational: 0, total: 0 };\n}\n\nfunction newStatusCounts(): StatusCounts {\n return {\n passed: newSeverityCounts(),\n failed: newSeverityCounts(),\n skipped: newSeverityCounts(),\n error: newSeverityCounts(),\n noImpact: newSeverityCounts(),\n };\n}\n\n/**\n * overallStatus is the canonical worst-wins roll-up of a requirement's result\n * statuses, delegated to @mitre/hdf-utilities worstStatus (error > failed >\n * passed > notApplicable > notReviewed; empty → notReviewed). No local rank\n * switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).\n */\nexport function overallStatus(results: RequirementResult[]): string {\n return worstStatus(results.map((r) => String(r.status)));\n}\n\n/**\n * deriveSeverity determines the severity string from impact and optional explicit\n * severity, using impactToSeverity. Both paths yield a value from the schema's\n * severity enum: an explicit informational and an impact-derived one are the same\n * thing and must not land in different buckets.\n */\nexport function deriveSeverity(impact: number, severity?: Severity | null): string {\n // Presence-based, matching Go DeriveSeverity's `if severity != nil`: an explicit\n // severity — including an empty string — is returned verbatim; only a\n // null/undefined severity derives from impact. Testing truthiness here would\n // send \"\" through the impact path and diverge from Go (bead 4908.20).\n if (severity != null) {\n return String(severity);\n }\n return impactToSeverity(impact);\n}\n\nfunction statusBucket(counts: StatusCounts, status: string): SeverityCounts {\n switch (status) {\n case 'passed':\n return counts.passed;\n case 'failed':\n return counts.failed;\n case 'error':\n return counts.error;\n case 'notApplicable':\n return counts.noImpact;\n case 'notReviewed':\n return counts.skipped;\n default:\n return counts.skipped;\n }\n}\n\nfunction addCount(counts: StatusCounts, status: string, severity: string): void {\n const sc = statusBucket(counts, status);\n sc.total++;\n switch (severity) {\n case 'critical':\n sc.critical++;\n break;\n case 'high':\n sc.high++;\n break;\n case 'medium':\n sc.medium++;\n break;\n case 'low':\n sc.low++;\n break;\n default:\n // Informational plus anything outside the enum: an unrecognized severity\n // is counted, never dropped, so a malformed document still gates.\n sc.informational++;\n }\n}\n\nfunction statusToThresholdKey(status: string): string {\n switch (status) {\n case 'passed':\n return THRESHOLD_PASSED;\n case 'failed':\n return THRESHOLD_FAILED;\n case 'notReviewed':\n return THRESHOLD_SKIPPED;\n case 'error':\n return THRESHOLD_ERROR;\n case 'notApplicable':\n return THRESHOLD_NO_IMPACT;\n default:\n return THRESHOLD_SKIPPED;\n }\n}\n\n/** CountControlsByStatusSeverity counts requirements by overall status and severity. */\nexport function countControlsByStatusSeverity(results: HDFResults): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n addCount(counts, overallStatus(req.results ?? []), deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * countControlsByStatus counts requirements by a caller-resolved status — the\n * injected-resolver twin of countControlsByStatusSeverity (which counts raw\n * result statuses with no override awareness). statusOf returns each\n * requirement's status in the schema vocabulary (passed/failed/notApplicable/\n * notReviewed/error); an empty or unrecognized value counts as skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status rollups\n * (e.g. compliance with and without agent-attributed overrides) without the\n * engine binding to any one status convention. Parity: go/compliance.go.\n */\nexport function countControlsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n addCount(counts, status, deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * agentOverrideCount counts the status overrides across a result set whose\n * applied-by identity type is \"agent\" — the detective count. Deterministic\n * from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny\n * signal. Parity: go/compliance.go AgentOverrideCount.\n */\nexport function agentOverrideCount(results: HDFResults): number {\n let count = 0;\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n for (const o of req.statusOverrides ?? []) {\n if (o.appliedBy?.type === 'agent') {\n count++;\n }\n }\n }\n }\n return count;\n}\n\n/** MapControlIDs builds control ID → status/severity mappings from a result set. */\nexport function mapControlIDs(results: HDFResults): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = overallStatus(req.results ?? []);\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: deriveSeverity(req.impact, reqSeverity(req)),\n });\n }\n }\n return mappings;\n}\n\n/**\n * mapControlIDsByStatus builds control ID → status/severity mappings using a\n * caller-resolved status — the injected-resolver twin of mapControlIDs (which\n * maps raw result statuses). statusOf returns each requirement's status in the\n * schema vocabulary; an empty or unrecognized value maps to skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status control\n * listings (the same injection pattern as countControlsByStatus). Parity:\n * go/compliance.go MapControlIDsByStatus.\n */\nexport function mapControlIDsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: deriveSeverity(req.impact, reqSeverity(req)),\n });\n }\n }\n return mappings;\n}\n\nfunction reqSeverity(req: EvaluatedRequirement): Severity | null {\n return (req.severity ?? null) as Severity | null;\n}\n\n/**\n * calculateCompliance returns the compliance percentage rounded to two decimals:\n * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.\n */\nexport function calculateCompliance(counts: StatusCounts): number {\n const relevant = counts.passed.total + counts.failed.total + counts.skipped.total + counts.error.total;\n if (relevant === 0) {\n return 0;\n }\n const pct = (counts.passed.total / relevant) * 100;\n return Math.round(pct * 100) / 100;\n}\n\n/**\n * normalizeLegacySeverity folds the pre-3.7 `none` key into `informational`. A\n * spec setting both is refused rather than resolved: the two name one bucket, so\n * silently honouring one would drop a bound the author wrote.\n */\nfunction normalizeLegacySeverity(config: ThresholdConfig): string[] {\n const violations: string[] = [];\n const sections: [string, ThresholdSeverity | undefined][] = [\n [THRESHOLD_PASSED, config.passed],\n [THRESHOLD_FAILED, config.failed],\n [THRESHOLD_SKIPPED, config.skipped],\n [THRESHOLD_ERROR, config.error],\n [THRESHOLD_NO_IMPACT, config.noImpact],\n ];\n for (const [name, ts] of sections) {\n if (!ts?.none) continue;\n if (ts.informational) {\n violations.push(\n `${name}: both 'none' and 'informational' are set; 'none' is the pre-3.7 spelling of the same bucket`,\n );\n continue;\n }\n ts.informational = ts.none;\n delete ts.none;\n }\n return violations;\n}\n\n/**\n * validateThresholds checks all threshold bounds against observed counts and\n * compliance, returning human-readable violation messages (empty when all pass).\n */\nexport function validateThresholds(\n config: ThresholdConfig,\n counts: StatusCounts,\n compliance: number,\n controlMap: ControlIDMapping[],\n): string[] {\n const violations: string[] = [];\n\n // Every construction path lands here, so the legacy spelling is resolved once\n // rather than in each caller.\n violations.push(...normalizeLegacySeverity(config));\n\n const actualControls = new Map<string, ControlIDMapping>();\n for (const m of controlMap) {\n actualControls.set(m.id, m);\n }\n\n if (config.compliance) {\n if (config.compliance.min !== undefined && compliance < config.compliance.min) {\n violations.push(`compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`);\n }\n if (config.compliance.max !== undefined && compliance > config.compliance.max) {\n violations.push(`compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`);\n }\n }\n\n violations.push(...checkSeverityThreshold(THRESHOLD_PASSED, config.passed, counts.passed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_FAILED, config.failed, counts.failed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_SKIPPED, config.skipped, counts.skipped, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_ERROR, config.error, counts.error, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_NO_IMPACT, config.noImpact, counts.noImpact, actualControls));\n\n return violations;\n}\n\nfunction checkSeverityThreshold(\n status: string,\n threshold: ThresholdSeverity | undefined,\n actual: SeverityCounts,\n actualControls: Map<string, ControlIDMapping>,\n): string[] {\n if (!threshold) {\n return [];\n }\n const violations: string[] = [];\n const check = (label: string, bound: ThresholdBound | undefined, actualCount: number): void => {\n if (!bound) {\n return;\n }\n const path = `${status}.${label}`;\n if (bound.min !== undefined && actualCount < bound.min) {\n violations.push(`${path}: ${actualCount} is below minimum ${bound.min}`);\n }\n if (bound.max !== undefined && actualCount > bound.max) {\n violations.push(`${path}: ${actualCount} exceeds maximum ${bound.max}`);\n }\n for (const expectedID of bound.controls ?? []) {\n const ac = actualControls.get(expectedID);\n if (!ac) {\n violations.push(`${path}: expected control ${expectedID} not found in results`);\n } else if (ac.status !== status || ac.severity !== label) {\n violations.push(\n `${path}: control ${expectedID} expected ${status}/${label} but found ${ac.status}/${ac.severity}`,\n );\n }\n }\n };\n\n check('critical', threshold.critical, actual.critical);\n check('high', threshold.high, actual.high);\n check('medium', threshold.medium, actual.medium);\n check('low', threshold.low, actual.low);\n check('informational', threshold.informational, actual.informational);\n check('total', threshold.total, actual.total);\n\n return violations;\n}\n","// Glob matching — the TypeScript peer of hdf-engine/go/safematch.go. Kept at\n// behavioural parity with the Go matcher.\n\nconst MAX_PATTERN_LENGTH = 256;\n\nconst REGEX_SPECIAL = new Set(['.', '+', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\\\']);\n\n/**\n * globToRegex converts a glob pattern (with * and ? wildcards) to an anchored\n * regular expression, escaping every other regex metacharacter exactly once. A\n * single pass avoids re-escaping the backslash introduced by escaping an earlier\n * metacharacter (the doubled-backslash defect that made any dotted pattern match\n * nothing).\n */\nexport function globToRegex(glob: string): string {\n let result = '^';\n for (const ch of glob) {\n if (ch === '*') {\n result += '.*';\n } else if (ch === '?') {\n result += '.';\n } else if (REGEX_SPECIAL.has(ch)) {\n result += '\\\\' + ch;\n } else {\n result += ch;\n }\n }\n return result + '$';\n}\n\n/**\n * safeGlobMatch converts a glob pattern to a regex and matches case-insensitively.\n * Returns false for over-length or invalid patterns (fail-safe), mirroring the\n * Go matcher's length cap and error handling.\n */\nconst byteEncoder = new TextEncoder();\n\n/** byteLength returns the UTF-8 byte length, matching Go's len(string). */\nfunction byteLength(s: string): number {\n return byteEncoder.encode(s).length;\n}\n\nexport function safeGlobMatch(s: string, pattern: string): boolean {\n // Cap on UTF-8 byte length (matching Go's len(pattern)), and — like Go's\n // compileSafeRegex — re-cap the EXPANDED regex, so an over-length glob or a\n // small glob that expands past the limit is rejected identically in both\n // languages (not just capped on the raw glob's UTF-16 length).\n if (byteLength(pattern) > MAX_PATTERN_LENGTH) {\n return false;\n }\n const rx = globToRegex(pattern);\n if (byteLength(rx) > MAX_PATTERN_LENGTH) {\n return false;\n }\n let re: RegExp;\n try {\n re = new RegExp(rx, 'i');\n } catch {\n return false;\n }\n return re.test(s);\n}\n","// Requirements query engine — the TypeScript peer of hdf-engine/go/filter.go.\n// A pure filter(results, options) with no shared mutable state, kept at\n// behavioural parity with the Go implementation (see test/query.test.ts, which\n// runs both over the same fixture).\n\nimport type { HDFResults, EvaluatedRequirement } from '@mitre/hdf-schema';\nimport { deriveSeverity } from './compliance.js';\nimport { safeGlobMatch } from './safematch.js';\n\n/**\n * FilterOptions configures a requirements query. Every filter input arrives here;\n * distinct filters combine with AND, repeated values within a filter with OR.\n * statusOf resolves a requirement's display status, injected so the engine stays\n * agnostic to the caller's status-string convention (undefined → empty status).\n */\nexport interface FilterOptions {\n status?: string[];\n severity?: string[];\n impact?: string;\n cci?: string[];\n nist?: string[];\n id?: string;\n tag?: string[];\n search?: string;\n baseline?: string;\n limit?: number;\n count?: boolean;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * A single query result row. baselineIndex and index are the match's position in\n * the result set (results.baselines[baselineIndex].requirements[index]) and are\n * the only unique identity a match has: baseline names repeat in shipped\n * converter output and requirement ids repeat within a baseline, so (baseline,\n * id) is not a key. Address the source requirement by position, never by name.\n */\nexport interface Match {\n id: string;\n title: string;\n status: string;\n impact: number;\n severity: string;\n baseline: string;\n baselineIndex: number;\n index: number;\n}\n\ntype FilterFunc = (control: EvaluatedRequirement, status: string, severity: string) => boolean;\n\n/**\n * filter returns the requirements across the result set's baselines that satisfy\n * options. Applies to requirement collections (results/baseline documents); the\n * calling adapter rejects document types that carry no requirements.\n */\nexport function filter(results: HDFResults, options: FilterOptions): Match[] {\n const filters = buildFilters(options);\n const matches: Match[] = [];\n\n for (const [baselineIndex, baseline] of (results.baselines ?? []).entries()) {\n if (options.baseline && !matchesGlob(baseline.name, options.baseline)) {\n continue;\n }\n for (const [index, control] of (baseline.requirements ?? []).entries()) {\n if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) {\n return matches;\n }\n\n const status = options.statusOf ? options.statusOf(control) : '';\n // Explicit STIG severity wins; impact-derived only as a fallback — the\n // canonical rule shared with the compliance counts (deriveSeverity), so\n // query rows and compliance never disagree on a requirement's severity.\n const severity = deriveSeverity(control.impact, control.severity ?? null);\n\n if (!applyFilters(control, status, severity, filters)) {\n continue;\n }\n\n matches.push({\n id: control.id,\n title: control.title ?? '',\n status,\n impact: control.impact,\n severity,\n baseline: baseline.name,\n baselineIndex,\n index,\n });\n }\n }\n return matches;\n}\n\nfunction buildFilters(options: FilterOptions): FilterFunc[] {\n const filters: FilterFunc[] = [];\n\n if (options.status && options.status.length > 0) {\n const statuses = options.status.map((s) => s.toLowerCase());\n filters.push((_c, s) => statuses.includes(s.toLowerCase()));\n }\n\n if (options.severity && options.severity.length > 0) {\n const severities = options.severity.map((s) => s.toLowerCase());\n filters.push((_c, _s, severity) => severities.includes(severity));\n }\n\n if (options.impact) {\n const [op, val] = parseImpactFilter(options.impact);\n filters.push((c) => compareImpact(c.impact, op, val));\n }\n\n if (options.cci && options.cci.length > 0) {\n const ccis = options.cci.map((c) => c.toUpperCase());\n filters.push((c) => ccis.some((cci) => tagContains(c.tags, 'cci', cci)));\n }\n\n if (options.nist && options.nist.length > 0) {\n const nist = options.nist;\n filters.push((c) => nist.some((n) => tagMatchesGlob(c.tags, 'nist', n)));\n }\n\n if (options.id) {\n const id = options.id;\n filters.push(\n (c) =>\n tagContains(c.tags, 'stig_id', id) ||\n tagContains(c.tags, 'gid', id) ||\n tagContains(c.tags, 'gtitle', id) ||\n c.id === id,\n );\n }\n\n if (options.tag && options.tag.length > 0) {\n const tagFilters: { key: string; value: string }[] = [];\n for (const t of options.tag) {\n const idx = t.indexOf(':');\n if (idx >= 0) {\n tagFilters.push({ key: t.slice(0, idx), value: t.slice(idx + 1) });\n }\n }\n if (tagFilters.length > 0) {\n filters.push((c) => tagFilters.some((tf) => tagMatchesGlob(c.tags, tf.key, tf.value)));\n }\n }\n\n if (options.search) {\n const search = options.search.toLowerCase();\n filters.push((c) => {\n if (c.id.toLowerCase().includes(search)) return true;\n if (c.title && c.title.toLowerCase().includes(search)) return true;\n for (const desc of c.descriptions ?? []) {\n if (desc.data.toLowerCase().includes(search)) return true;\n }\n return false;\n });\n }\n\n return filters;\n}\n\nfunction applyFilters(\n control: EvaluatedRequirement,\n status: string,\n severity: string,\n filters: FilterFunc[],\n): boolean {\n return filters.every((f) => f(control, status, severity));\n}\n\n// DECIMAL_FLOAT is the shared impact-filter operand grammar — a plain decimal:\n// optional sign, digits with an optional fraction (or a leading-dot fraction),\n// optional decimal exponent. It excludes the forms JS Number() accepts but that\n// make no sense as a 0.0–1.0 threshold and diverge from Go strconv.ParseFloat:\n// hex/binary/octal integers (0x1f→31, 0b101→5, 0o17→15) and Infinity. The Go\n// engine applies the identical pattern so a filter is accepted or rejected the\n// same in both languages (bead 4908.15).\nconst DECIMAL_FLOAT = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n// parseDecimal parses a plain-decimal operand, returning null for anything\n// outside the shared grammar (including overflow to Infinity, e.g. '1e400', so\n// Go's ParseFloat ErrRange rejection is mirrored).\nfunction parseDecimal(s: string): number | null {\n if (!DECIMAL_FLOAT.test(s)) return null;\n const v = Number(s);\n return Number.isFinite(v) ? v : null;\n}\n\n// An invalid operand safe-degrades to ('=', NaN), which compareImpact treats as\n// matching NOTHING — mirroring the Go engine's `return ok && compareImpact(...)`.\n// It must never coerce to ('=', 0), which silently returns confidently-wrong\n// impact==0 rows for a typo'd or garbage filter.\nexport function parseImpactFilter(f: string): [string, number] {\n const trimmed = f.trim();\n for (const op of ['>=', '<=', '>', '<', '=']) {\n if (trimmed.startsWith(op)) {\n const v = parseDecimal(trimmed.slice(op.length).trim());\n return v === null ? ['=', NaN] : [op, v];\n }\n }\n const v = parseDecimal(trimmed);\n return v === null ? ['=', NaN] : ['=', v];\n}\n\nexport function compareImpact(impact: number, op: string, val: number): boolean {\n switch (op) {\n case '>':\n return impact > val;\n case '>=':\n return impact >= val;\n case '<':\n return impact < val;\n case '<=':\n return impact <= val;\n case '=':\n return impact === val;\n default:\n return false;\n }\n}\n\nexport function tagContains(tags: Record<string, unknown>, key: string, value: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n const want = value.toLowerCase();\n if (typeof tagVal === 'string') {\n return tagVal.toLowerCase() === want;\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && item.toLowerCase() === want);\n }\n return false;\n}\n\nexport function tagMatchesGlob(tags: Record<string, unknown>, key: string, pattern: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n if (typeof tagVal === 'string') {\n return safeGlobMatch(tagVal, pattern);\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && safeGlobMatch(item, pattern));\n }\n return false;\n}\n\n/** matchesGlob reports whether s matches the glob pattern (case-insensitive). */\nexport function matchesGlob(s: string, pattern: string): boolean {\n return safeGlobMatch(s, pattern);\n}\n","// Document loader engine core — the TypeScript peer of hdf-engine/go/loader.go,\n// kept at behavioural parity (see loader.test.ts + the Go parity test, which\n// run both over the same fixtures). Pure and schema-typed: size-guard first,\n// wire-format + document-type detection, then the canonical parse for the\n// results/baseline types. No cache, no degraded envelope — those are MCP\n// concerns layered on top in hdf-cli/internal/mcp/loader.\n\nimport type { HDFResults, HDFBaseline } from '@mitre/hdf-schema';\nimport { validateInputSize } from '@mitre/hdf-utilities';\nimport { parseResults, parseBaseline } from '@mitre/hdf-parsers';\nimport { detect, type HdfDocType } from './detect.js';\n\n/** Wire encoding of loader input (parity with Go InputFormat). */\nexport type InputFormat = 'json' | 'ndjson';\n\nexport interface LoadResult {\n format: InputFormat;\n docType: HdfDocType;\n results?: HDFResults;\n baseline?: HDFBaseline;\n /** Non-empty when detected as results/baseline but the parse/validate failed. */\n parseError?: string;\n valid: boolean;\n}\n\n/**\n * load is the schema-typed loader core. In order: validateInputSize (FIRST,\n * before any parse; maxSize <= 0 uses the default), wire-format detection\n * (JSON vs NDJSON), document-type detection (detect), then the canonical\n * hdf-parsers parse for the results and baseline types. Other types are\n * detected but not parsed here.\n */\nexport function load(input: string | Uint8Array, maxSize = 0): LoadResult {\n validateInputSize(input, maxSize); // first op — throws on oversize\n\n const text = typeof input === 'string' ? input : new TextDecoder().decode(input);\n const result: LoadResult = {\n format: detectFormat(text),\n docType: detect(text),\n valid: false,\n };\n\n if (result.docType === 'results') {\n const r = parseResults(text);\n if (r.success && r.data) {\n result.results = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n } else if (result.docType === 'baseline') {\n const r = parseBaseline(text);\n if (r.success && r.data) {\n result.baseline = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n }\n\n return result;\n}\n\n/**\n * detectFormat classifies input as a single JSON document or newline-delimited\n * JSON, consistent with the Go core: NDJSON is two or more non-blank lines that\n * each independently parse as a complete JSON value. A pretty-printed single\n * object stays 'json' (its first line is not itself a complete JSON value).\n */\nexport function detectFormat(text: string): InputFormat {\n const lines = text.split('\\n').filter((l) => l.trim() !== '');\n const [first, second] = lines;\n if (first === undefined || second === undefined) {\n return 'json';\n }\n if (isCompleteJSON(first) && isCompleteJSON(second)) {\n return 'ndjson';\n }\n return 'json';\n}\n\n// isCompleteJSON reports whether s is a single complete JSON value with no\n// trailing content — the per-line test the NDJSON classifier applies. JSON.parse\n// already rejects trailing garbage, so a successful parse is sufficient.\nfunction isCompleteJSON(s: string): boolean {\n try {\n JSON.parse(s);\n return true;\n } catch {\n return false;\n }\n}\n","// Evidence-verify engine — the TypeScript peer of hdf-engine/go/evidence.go.\n// Pure, filesystem-agnostic core of `hdf evidence verify` (ADR-0007 §11):\n// content-checksum classification and plan/results completeness. All filesystem\n// IO and path confinement stay in the caller, injected as a FetchFn. Kept at\n// behavioural parity with the Go implementation (see test/evidence.test.ts,\n// which runs both over the same fixtures).\n\nimport { createHash } from 'node:crypto';\nimport { agentOverrideCount } from './compliance.js';\nimport type { HDFResults } from '@mitre/hdf-schema';\n\n/** Classifies a single content entry's checksum verification. */\nexport type ChecksumStatus = 'match' | 'mismatch' | 'skipped' | 'error';\n\n/** One content entry of an evidence package: a referenced document and its\n * recorded checksum ('' when the entry carries none). */\nexport interface EvidenceContent {\n uri: string;\n type: string;\n checksum: string;\n}\n\n/** The verification outcome for one content entry. */\nexport interface ChecksumResult {\n uri: string;\n type: string;\n status: ChecksumStatus;\n expected?: string;\n actual?: string;\n error?: string;\n}\n\n/** Reports which planned baselines are covered by results. */\nexport interface CompletenessResult {\n planned: string[];\n covered: string[];\n missing: string[];\n complete: boolean;\n}\n\n/** Resolves a content URI to its bytes. The caller owns path confinement\n * (HDF_MCP_ROOT for the MCP, the package directory for the CLI). Throws when the\n * uri cannot be read. */\nexport type FetchFn = (uri: string) => Uint8Array;\n\ntype RawObject = Record<string, unknown>;\n\n/** Go decodes into a typed struct, so a JSON `null` document leaves zero values\n * while a wrong-typed one is a decode error. These three helpers give the TS\n * peer the same split instead of asserting a shape onto untrusted input. */\nfunction parseDocument(text: string, what: string): RawObject {\n const doc: unknown = JSON.parse(text);\n if (doc === null) return {};\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(doc)} into an object`);\n }\n return doc as RawObject;\n}\n\nfunction objectArray(value: unknown, what: string, field: string): RawObject[] {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(value)} into ${field}`);\n }\n return value.map((entry: unknown) => {\n if (entry === null) return {};\n if (typeof entry !== 'object' || Array.isArray(entry)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(entry)} into a ${field} entry`);\n }\n return entry as RawObject;\n });\n}\n\nfunction str(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction describe(value: unknown): string {\n return Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;\n}\n\n/** Extracts the planRef and content entries from an evidence-package document. */\nexport function parseEvidencePackage(pkg: string): { planRef: string; contents: EvidenceContent[] } {\n const doc = parseDocument(pkg, 'evidence package');\n const contents: EvidenceContent[] = objectArray(doc.contents, 'evidence package', 'contents').map((c) => {\n const checksum = c.checksum;\n return {\n uri: str(c.uri),\n type: str(c.type),\n checksum: typeof checksum === 'object' && checksum !== null ? str((checksum as RawObject).value) : '',\n };\n });\n return { planRef: str(doc.planRef), contents };\n}\n\n/** Verifies each content entry's sha256 against fetch(uri), preserving entry\n * order. No checksum → skipped; a fetch throw → error; hash mismatch → mismatch\n * (carrying expected+actual). */\nexport function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): ChecksumResult[] {\n return contents.map((c) => {\n const r: ChecksumResult = { uri: c.uri, type: c.type, status: 'skipped' };\n if (c.checksum === '') {\n return r;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch (e) {\n return { ...r, status: 'error', error: e instanceof Error ? e.message : String(e) };\n }\n const actual = sha256Hex(data);\n if (actual === c.checksum) {\n return { ...r, status: 'match' };\n }\n return { ...r, status: 'mismatch', expected: c.checksum, actual };\n });\n}\n\n/** Extracts assessment baselineRefs from a plan document, deduped in first-seen\n * order. */\nexport function plannedBaselineRefs(plan: string): string[] {\n const doc = parseDocument(plan, 'plan');\n const refs = objectArray(doc.assessments, 'plan', 'assessments')\n .map((a) => str(a.baselineRef))\n .filter((s) => s !== '');\n return dedupe(refs);\n}\n\n/** Extracts baseline names from a results document, deduped in first-seen order. */\nexport function coveredBaselineNames(results: string): string[] {\n const doc = parseDocument(results, 'results');\n const names = objectArray(doc.baselines, 'results', 'baselines')\n .map((b) => str(b.name))\n .filter((s) => s !== '');\n return dedupe(names);\n}\n\n/** Concatenates the covered baseline names of every hdf-results document the\n * package references, in entry order. An entry that cannot be fetched or parsed\n * is skipped: checksum verification is what reports a read failure, and a\n * partial coverage list is what the completeness diff needs. */\nexport function coveredBaselinesInPackage(contents: EvidenceContent[], fetch: FetchFn): string[] {\n const covered: string[] = [];\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n covered.push(...coveredBaselineNames(text));\n } catch {\n return;\n }\n });\n return covered;\n}\n\n/** Sums the agent-attributed override count across every hdf-results document\n * the package references. Unreadable or unparseable entries are skipped. */\nexport function agentOverridesInPackage(contents: EvidenceContent[], fetch: FetchFn): number {\n let total = 0;\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n total += agentOverrideCount(JSON.parse(text) as HDFResults);\n } catch {\n return;\n }\n });\n return total;\n}\n\n/** Fetches each referenced hdf-results document in entry order, skipping\n * entries that carry no uri or cannot be read. */\nfunction forEachResultsDocument(\n contents: EvidenceContent[],\n fetch: FetchFn,\n visit: (text: string) => void\n): void {\n for (const c of contents) {\n if (c.type !== 'hdf-results' || c.uri === '') {\n continue;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch {\n continue;\n }\n visit(new TextDecoder().decode(data));\n }\n}\n\n/** Diffs planned baseline refs against covered baseline names. A planned ref is\n * covered when some results baseline shares its name. Missing is sorted so the\n * outcome is deterministic across languages and runs. */\nexport function completeness(planned: string[], covered: string[]): CompletenessResult {\n const coveredSet = new Set(covered);\n const missing = planned.filter((p) => !coveredSet.has(p)).sort();\n return { planned, covered, missing, complete: missing.length === 0 };\n}\n\nfunction sha256Hex(data: Uint8Array): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\nfunction dedupe(input: string[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const s of input) {\n if (!seen.has(s)) {\n seen.add(s);\n out.push(s);\n }\n }\n return out;\n}\n"],"mappings":";;;;AAIA,MAAa,gBAAgB;;;;ACgC7B,MAAa,aAAa;AAC1B,MAAa,qBAAqB;AAClC,MAAa,wBAAwB;AAErC,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,MAAM,SAAqC;CACzD,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,MAAM,mBAAmB;CAGrC,MAAM,YAAiC,CAAC;CACxC,MAAM,aAA0B,CAAC;CACjC,MAAM,WAA2B,CAAC;CAClC,MAAM,gCAAgB,IAAI,IAAY;CACtC,MAAM,aAAwC,CAAC;CAC/C,MAAM,kCAAkB,IAAI,IAAsB;CAClD,IAAI;CAEJ,QAAQ,SAAS,KAAK,UAAU;EAC9B,MAAM,SAAS,WAAW,IAAI,KAAK,KAAK;EACxC,MAAM,UAAU,YAAY,IAAI,GAAG;EAEnC,KAAK,MAAM,KAAK,IAAI,IAAI,aAAa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IAAI;EACJ,IAAI;GACF,OAAO,MAAM,EAAE,GAAG;EACpB,QAAQ;GACN;EACF;EACA,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;CACtC;AACF;;;;AAKA,SAAgB,aAAa,SAAmB,SAAuC;CACrF,MAAM,aAAa,IAAI,IAAI,OAAO;CAClC,MAAM,UAAU,QAAQ,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK;CAC/D,OAAO;EAAE;EAAS;EAAS;EAAS,UAAU,QAAQ,WAAW;CAAE;AACrE;AAEA,SAAS,UAAU,MAA0B;CAC3C,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK;AACvD;AAEA,SAAS,OAAO,OAA2B;CACzC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,KAAK,OACd,IAAI,CAAC,KAAK,IAAI,CAAC,GAAG;EAChB,KAAK,IAAI,CAAC;EACV,IAAI,KAAK,CAAC;CACZ;CAEF,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mitre/hdf-engine",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.7.0-rc.1",
|
|
4
4
|
"description": "Shared schema-typed read-side engines for HDF documents — detection, query/filtering, and compliance rollups",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -25,12 +25,13 @@
|
|
|
25
25
|
"author": "MITRE Corporation",
|
|
26
26
|
"license": "Apache-2.0",
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@mitre/hdf-schema": "^3.
|
|
29
|
-
"@mitre/hdf-utilities": "^3.
|
|
30
|
-
"@mitre/hdf-parsers": "^3.
|
|
28
|
+
"@mitre/hdf-schema": "^3.7.0-rc.1",
|
|
29
|
+
"@mitre/hdf-utilities": "^3.7.0-rc.1",
|
|
30
|
+
"@mitre/hdf-parsers": "^3.7.0-rc.1"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"@mitre/hdf-
|
|
33
|
+
"@mitre/hdf-fixtures": "^3.7.0-rc.1",
|
|
34
|
+
"@mitre/hdf-validators": "^3.7.0-rc.1"
|
|
34
35
|
},
|
|
35
36
|
"engines": {
|
|
36
37
|
"node": ">=22.0.0"
|